I have a simple Parent Functional Component (App.js) and a child Functional component (counters.jsx), I want to pass a signal/prop from child to parent. I want to send the props as an argument to another function in my child component. I can easily trigger parent function by onClick={props.parentCallback}. but if I send the same props as an argument to another function in child component, I get the error "Expected an assignment or function call and instead saw an expression no-unused-expressions"
//This is parent Component, App.js
function App() {
return (
<div className="App">
<Counters parentCallback = {handleCallback}/>
</div>
);
}
const handleCallback = () => {
console.log("CALLED FRM CHILD");
}
//This is Child Component- Counters.jsx
function Counters (props) {
return (
<div>
<button onClick={ ()=> parentHandler(props) }>CALL PARENT</button><hr/>
{//onClick={props.parentCallback} - This works well}
</div>
);
};
function parentHandler (props) {
props.parentCallback; // This line throws the aforementioned error
}
no-unused-expressions usually means that you evaluated a value but never used. This rule aims to eliminate unused expressions.
For example if(true) 0
In your case you are calling props.parentCallback without parenthesis, leaving unused. Either you add parenthesis after your function call like this props.parentCallback() or return some value at the end. By that your eslint error will disappear.
Also onClick={props.parentCallback} - This works well because you are just passing a reference of your function to the parent Component. But here onClick={ ()=> parentHandler(props) } you are creating a new inline function on each render.
You are just referencing the function. Not calling it. You can modify parentHandler function as
function parentHandler (props) {
props.parentCallback()
}
Thank u for ur answer guys, but none of the answer is exactly what I wanted. Finally, I got the answer myself as it is:
Do you need the function to run now?
Then add the () to execute it
Do you need to function to be referenced so it is called later?
Do not add the ().
More example:
onClick=parentCallback() means call "parentCallback() ASAP, and set its return value to onClick".
On the other hand, onClick=parentCallback means "onClick is an alias for parentCallback. If you call onClick(), you get the same results as calling parentCallback()"
I found it by googling "function call and function reference".