How To Call Child Function From Parent Component In React
React
31/07/2021
One way to call a child component's function from its parent is with the help of the useRef hook.
Here's the gist of it: We pass a Ref (e.g. childFunc
) to a child 🧒 component and assign the desired function to the Ref's current
key. This then gives you access to that very function in the parent component.
Take a look at this interactive example:
Pay attention to how childFunc
is passed down: a custom props is used instead of ref
as the latter would otherwise return a DOM element.