Exposing React Component functions with fowardRef and useRef

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:

  1. React.forwardRef is a function that receives a component as argument, so you should wrap the component function with it
  2. 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
  3. 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:

  1. Create a ref using the useRef hook. The argument is the initial ref value.
  2. Link the created ref with the child component using the component prop ref <Component ref={createdRef} />
  3. 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.

Deixe um comentário

O seu endereço de e-mail não será publicado. Campos obrigatórios são marcados com *