Home > database >  How do I call component's inner function from its parent component in React
How do I call component's inner function from its parent component in React

Time:10-07

const Parent = (props) => {
  return <Child {...props} />
};

const Child = (props) => {
  function handleClick() {
   ...
  }
  return <div {...props}><a onClick={handleClick}>link</a></div>;
}

I want to call the child's handleClick function from within its parent component (that has some custom events). My first guess was to use a state in a parent component and invoke the handleClick event in a useEffect callback:

const Parent = (props) => {
  const [toggle, setToggle] = useState(false);
  return <Child toggle={toggle} {...props} />
};

const Child = (props) => {
  useEffect(() => { if (toggle) handleClick() }, [toggle]);
  function handleClick() { 
    ... 
  }      
  return <div {...props}><a onClick={handleClick}>link</a></div>;
}

However I believe this is not what useEffect is created for and is a poor solution all around.

CodePudding user response:

You can define the handleClick function in the Parent and also use it in the Child. that way you'll call the same function when you trigger the custom events in the Parent, as well as when you click the Child:

const Parent = () => {
  const click = () => {
    console.log("Clicked!");
  };

  return (
    <div className="App">
      <button onClick={click}>Custom event!</button>
      <Child handleClick={click} />
    </div>
  );
}

const Child = ({ handleClick }) => (
  <div>
    <button onClick={handleClick}>Hello</button>
  </div>
);

CodePudding user response:

If you don't want to lift up your handler function then context API is the solution.

  • Related