Home > other >  Accessing props in separate function in a functional component
Accessing props in separate function in a functional component

Time:12-07

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 
      }  

CodePudding user response:

You are just referencing the function. Not calling it. You can modify parentHandler function as

function parentHandler (props) {
  props.parentCallback()
  } 

CodePudding user response:

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.

  • Related