React components use props to communicate between parent and children, this is the recommended way of interacting. But sometimes is desirable to have internal component functions exposed from children to parent. This can save some time and improve the readability.
The source code for this example can be found here.
Exposing component functions with forwardRef
First we are going to use React.forwardRef to expose the desired internal component functions. Follow the steps:
- React.forwardRef is a function that receives a component as argument, so you should wrap the component function with it
- Declare a second argument in the component function. The first argument is props, as always. The second will be a ref, that we will use feed our functions afterward
- Create an object with the functions you want to expose and assing to ref.current
Below is a Counter component showing how to expose addOne function.
Using exposed child functions in a parent component
Now that we have our functions exposed, it’s time to use them. To do that follow the steps:
- Create a ref using the useRef hook. The argument is the initial ref value.
- Link the created ref with the child component using the component prop ref <Component ref={createdRef} />
- Use the functions with: createdRef.current.myFunction()
Below is the parent component code, showing how to access a child component ref, access the functions and make use of them.