0
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.

sdvnksv
  • 9,350
  • 18
  • 56
  • 108
  • Is it possible to put the handleClick function in the Parent component, and pass it to Child component? – The KNVB Oct 07 '22 at 09:31
  • @TheKNVB the `handleClick` function contains a bunch of state dependent logic from the Child component, so it's not really possible to move it up the tree. – sdvnksv Oct 07 '22 at 09:34
  • Does this answer your question? [When to use useImperativeHandle, useLayoutEffect, and useDebugValue](https://stackoverflow.com/questions/57005663/when-to-use-useimperativehandle-uselayouteffect-and-usedebugvalue) – Giorgi Moniava Oct 07 '22 at 09:39
  • https://stackoverflow.com/questions/37949981/call-child-method-from-parent – Yone Oct 07 '22 at 09:40
  • Does this answer your question? [Call child method from parent](https://stackoverflow.com/questions/37949981/call-child-method-from-parent) – Yone Oct 07 '22 at 10:35

2 Answers2

0

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>
);
Pedro Filipe
  • 995
  • 1
  • 8
  • 17
0

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

Arifur Rahaman
  • 534
  • 1
  • 2
  • 8