I have been using ReactJs for a couple of days now. And I find some syntax a bit curious.
For example, sometimes I have to call a function this way:
{this.functionName}
Without the parentheses at the end.
And sometimes I have to call it like this:
{this.functionName()}
Like in this example:
<button onClick={this.streamCamVideo}>Start streaming</button>
<h1>{this.logErrors()}</h1>
See the difference between calling this.streamCamVideo and this.logErrors().
Can someone please provide an explanation for this?
EDIT 1:
As requested, here are their definitions :
streamCamVideo() {
var constraints = { audio: true, video: { width: 1280, height: 720 } };
navigator.mediaDevices
.getUserMedia(constraints)
.then(function(mediaStream) {
var video = document.querySelector("video");
video.srcObject = mediaStream;
video.onloadedmetadata = function(e) {
video.play();
};
})
.catch(function(err) {
console.log(err.name + ": " + err.message);
}); // always check for errors at the end.
}
logErrors(){
return(navigator.mediaDevices.toString())
}
{this.streamCamVideo} is a reference to the streamCamVideo function. You can think of this.streamCamVideo as a variable whose value is a function. Think about it like this:
const myVariable = 'some text'
const myOtherVariable = function() {
console.log("You are inside the myOtherVariable function");
}
Both myVariable and myOtherVariable are variables. One has the value of a string, the other has the value of a function. Let's say you want to pass both of these variables to another function:
const anotherVariable = function(aStringVariable, aFunctionVariable) {
console.log(aStringVariable, aFunctionVariable)
}
anotherVariable(myVariable, myOtherVariable)
You might see something like this logged to the console:
some text
[Function]
Notice that you don't ever see the text "You are inside the myOtherVariable function" logged to the console. That's because the myOtherVariable function is never called. It's just passed to the anotherVariable function. In order to call the function, you would need to do something like this:
const anotherVariable = function(aStringVariable, aFunctionVariable) {
aFunctionVariable()
console.log(aStringVariable, aFunctionVariable)
}
Notice the parentheses after aFunctionVariable()? That's what it looks like to actually call a function. So in this case, you'd see something like this logged to the console:
You are inside the myOtherVariable function
some text
[Function]
The function is actually being called.
So in your example:
<button onClick={this.streamCamVideo}>Start streaming</button>
<h1>{this.logErrors()}</h1>
this.streamCamVideo is just being passed as a variable to the <button> element. When the button is clicked, whatever has been assigned to onClick will be executed. That's when the function you passed as a variable will actually be called.
Also, notice the parentheses after this.logErrors()? The logErrors function is being executed. It is not being passed as a variable to anything.
{this.functionName} means referencing the function on a particular trigger. this way function will get called only when triggered.
{this.functionName()} is an actual function call, this method can be used to pass arguments. this function call will get called when page renders. This way function will get called repeatedly without any triggers. To stop that repeated function call we can use callback. like the following,
{() => this.functionName()}. this way the function will get executed only once.
{this.functionName} is used a reference type and it does not create instance on every render but {this.functionName()} is creates an instance of functionName on every render
<button onClick={this.streamCamVideo}>Start streaming</button>
Here if you use this.streamCamVideo Now it uses the reference type it does not create an instance of streamCamVideo but instead of if you use like this
<button onClick={()=>{this.streamCamVideo()}}>Start streaming</button>
Now it creates an instance of streamCamVideo instead of using the reference of streamCamVideo.
Creating an instance on every render it slows the performance of your application
Moreover, When evaluated, the first one is just a reference to the function, in the second case the function gets executed, and the expression will be evaluated to be the return value of the function.
We can use this.logErrors() when you want the function to be invoked and its result returned immediately.
In React, we typically follow this approach to split parts of your JSX code to a separate function for readability or reusability.
For Example:
render() {
someFunction() {
return <p>Hello World</p>;
}
return (
<div>
{this.logErrors()}
</div>
);
}
We can use this.streamCamVideo when you want only to pass the reference to that function to do something else.
In React, this is used while handling an event handler which can be passed down to another child-component via props, so that component can call the event handler when it needs to or when it gets triggered.
For Example:
class myExample extends React.Component {
streamCamVideo() {
console.log("button clicked!");
}
render() {
return (
<div>
<Button someCustomFunction={this.streamCamVideo} />
</div>
);
}
}
class Button extends React.Component {
render() {
return (
<button onClick={this.props.someCustomFunction}>Click me</button>
);
}
}
...
this.functionName(args) {
...
}
When its called like
... onClick={this.functionName}
The react component accepts like
function SomeReactComponent({ onClick }) {
...
so that onClick function can be called like
...
onClick(someEvent);
...
so that your function can use those args
...
this.functionName(someEvent) {
...
}
When it calls like this
... onClick={this.functionName()}
onClick accepts the result of functionName, which should also be a function in this case.
One is attribute, another with "()" is function.
Related
I want to dynamically return different values based on the event that changes the value of var inside the constructor function. When constructor function is created I get the return of the default value which is equal to doA, when I invoke it the first time, I get a call to someFunction from doA. When the event happens, I can see that event variable updates it is reference to refer to doB function, however, when I invoke someFunction a second time, I still get a call to doA instead of doB. Any suggestion of can I achieve what I intent?
Thank you in advance
PS - the code bellow is not a working code, it just a representation of what I am trying to achieve
function doA(){
function someFunction(){};
function someFunctionB(){};
}
function doB(){
function someFunction(){};
function someFunctionB(){};
}
function Main(){
var event;
addEventListener('change', (event) => {
if(someCondition){
event = doA();
}
if(otherCondtion){
event = doB();
}
});
function someOtherFunction(){
}
return{
...event,
someOtherFunction
}
}
const main = new Main();
main.someFunction(); //calling someFunction from doA
//event changes here
main.someFunction() //intent to call someFuntion doB but still calling someFunction from doA
'''
I am currently working on a project where I want to deference an array of functions (function references) and excecute the function.
This does only work, if I don't call another class method within the function.
Otherwise I get "Uncaught TypeError" and I can't figure out how to solve this error.
Here's my code sample 'working' the same way my original project does:
After calling function2 the engine cannot find this.log...
Do you have ideas? Thank you very much in advance.
KR, Robert
class ArrayWithFunctions {
constructor() {
this.functionTable = [
this.function1,
this.function2,
];
}
execute(index) {
return (this.functionTable[index])();
}
log(chars) {
console.log(chars);
}
function1() {
console.log('I am Function 1.');
}
function2() {
this.log('I am Function 2.');
}
}
let example = new ArrayWithFunctions();
example.execute(0);
example.execute(1);
This is an example of Javascript's execution contexts in action. In this situation, to avoid losing the correct reference to the class, you can bind the functions when putting them inside the array, or initialize them as arrow functions:
Example 1: Bind them in the constructor:
constructor() {
this.functionTable = [
this.function1.bind(this),
this.function2.bind(this),
];
}
Example 2: Create them as arrow functions:
class ArrayWithFunctions {
// ...
function1 = () => {
console.log('I am Function 1.');
}
function2 = () => {
this.log('I am Function 2.');
}
}
You can use arrow functions to dodge scoping issues:
function2 = () => {
this.log('I am function 2.');
}
Related: How to access the correct `this` inside a callback (and you might also want to take a look at How does the "this" keyword work?).
In this case you can simply set the correct this value by calling the function with .call:
return this.functionTable[index].call(this);
I have a problem where if i want to add a parameter to my click attribute then it calls the function as soon as it renders
here is my test html:
return html`
<button class="menu-btn" #click="${this._OpenSubMenu(1)}>test</button>"
`;
}
And the function:
_OpenSubMenu(test:number) {
console.log("Hello")
}
This output Hello as soon as the page is rendered.
So how can i avoid this while still adding a parameter to my function?
You need to make your function return a function. Your click function will then execute the returned function, and due to closure's will still have access to the params.
eg..
_OpenSubMenu(test:number) {
var that = this;
return function () {
console.log("Hello");
//test is also a closure so you can use here
//that will equal this
}
}
If you want access to this, you could also use an arrow function
_OpenSubMenu(test:number) {
return () => {
console.log("Hello");
//test is also a closure so you can use here
//this will also still be valid here
}
}
I would like to know why in certain types of events, such as onClick, I have to declare an anonymous function to execute the onClick if my function contains arguments.
Example: https://codesandbox.io/s/suspicious-ramanujan-v998u
export default function App() {
const myValue = "MY VALUE";
const handleClick = (anyString) => {
console.log(anyString);
};
const anotherClick = () => {
console.log("It works");
};
return (
<>
<Button onClick={() => anotherClick()} color="primary">
Works without arguments <-- Works
</Button>
<Button onClick={anotherClick} color="secondary">
Works without arguments <-- Works
</Button>
<Button onClick={() => handleClick(myValue)} color="primary">
Works with arguments <-- Works
</Button>
<Button onClick={handleClick(myValue)} color="secondary">
Does NOT work with arguments <-- Does NOT work
</Button>
</>
);
}
Question
I do not understand why I have to create an anonymous function if the function I want to execute has arguments.
Why do I have to do onClick={() => handleClick(myString)}?
Why onClick={handleClick(myString)} is not enough?
onClick accepts a callback i.e. a function that will be called when the button is clicked.
anotherClick is a function so it works, as it's being called properly
() => anotherClick() is equivalent to this
...
const myTempFunction = () => {
anotherClick();
}
...
onClick={myTempFunction}
Since you're ultimately passing a function to onClick it works
() => handleClick(myValue) same reason as above, and equivalent code is
...
const myTempFunction = () => {
handleClick(myValue);
}
...
onClick={myTempFunction}
handleClick(myValue), now here you're actually calling the function the you're passing the value that the function returns to onClick, not the function itself,
the equivalent code would be
...
const myResult = handleClick(myValue); // This is the result of calling the function
...
onClick={myResult} // myResult isn't a function, it's the return value of handleClick(myValue)
Since you're not actually passing a function to onClick, onClick can't be called and it doesn't work
This is due to design of the syntax extension what we called JSX Template extension. When it comes to event Handling inside JSX, it needs a reference to the callback function which is going to trigger after specific event happens.
This is before JSX is converted in to JavaScript Via Babel
return (
<div>
<Button onClick={anotherClick} color="secondary">
Works without arguments
</Button>
<Button onClick={handleClick(myValue)} color="secondary">
Does NOT work with arguments
</Button>
</div>
);
This is after the Babel Conversion.
return React.createElement("div", null, React.createElement(Button, {
onClick: anotherClick,
color: "secondary"
}, "Works without arguments"),
React.createElement(Button, {
onClick: handleClick(myValue),
color: "secondary"
}, "Does NOT work with arguments"));
You can clearly see here that second click handler is executing the function directly rather than passing a callback function to React.createElement. Because internally React Element need a callback function to get pass to this function and you are just try to execute that function instead of parsing the reference.
You are supposed to specify a function in onClick={func}. "func" is only referring to a variable.
When saying onClick={func()}, you are adding the return value of func(), rather than specifying function func() { } to be executed, when the event is emitted.
When the button is clicked, the function, specified in onClick={} is executed.
This is what you are doing:
let emit = function () { };
button.addEventListener('click', emit());
When the button is clicked, it tries to call undefined as a function, since the function emit() has returned undefined.
In the doc for (Handling Component Events), there is an example
function ActionLink() {
function handleClick(e) {
e.preventDefault();
console.log('The link was clicked.');
}
return (
<a href="#" onClick={handleClick}>
Click me
</a>
);
}
So we could see that every value passed to event handler props (onClick, onFocus,...) must be a method (or you may say function)
Go back to your example, in the first 3, you pass function, so it definitely works. But with the 4th, first to say handleClick is simply a method that return undefined, so when you call onClick={handleClick(myValue)}, it similar to onClick={undefined}, which resulted in nothing happened
const handleClick = (anyString) => {
console.log(anyString);
};
// ...
<Button onClick={handleClick(myValue)} color="secondary">
Does NOT work with arguments <-- Does NOT work
</Button>
I have an array with functions: var ranArray = [funct1(), funct2()] and the functions themselves:
function funct1() {
document.write("hello");
};
function funct2() {
document.write("hi");
};
I am trying to make it so that whenever a button is pressed, either funct1 or funct2 is executed.
However, without me even pressing the button, on the page I see my button and "hellohi". Here is the function for the randomization:
function getFunctions() {
return ranArray[Math.floor(Math.random * ranArray.length)];
};
and here is the HTML:
<button type="button" name="ranButton" id="ranButton" onclick="getFunctions();">Random Button</button>
Firstly you need to store the function references ([funct1, funct2]), the () will immediately call the functions. Next you can use .call() to call the function, or more simply add () at the end of ranArray[Math.floor(Math.random() * ranArray.length)] as #jfriend00 mentioned. Also note that Math.random needs to be Math.random().
var ranArray = [funct1, funct2];
function funct1() {
document.write("hello");
};
function funct2() {
document.write("hi");
};
function getFunctions() { // Note you don't really need a 'return' here
return ranArray[Math.floor(Math.random() * ranArray.length)]();
};
Demo
Also the use of document.write() here is overwriting the DOM. So I don't recommend it, rather you may want to place this content inside a element. If you have some element of the id #foo you could instead set the text of that DOM element:
document.getElementById("foo").textContent = "...";
Demo 2
Your array declaration is actually calling funct1 and funct2 and trying to store the return values in the array. What you want is an array of functions. Remove the parentheses so the functions themselves are stored in the array rather than the return values. It should look like this:
var ranArray = [funct1, funct2];