Categories
React Answers

How to Add Refs to React Components by Forwarding Refs?

Spread the love

Sometimes, we want to add refs to React components.

In this article, we’ll look at how to add refs to React components.

Add Refs to React Components by Forwarding Refs

Forwarding refs means that we are getting the refs from a child component from a parent component.

For instance, if we want to get the ref of a button that resides in a custom button component, we can write the following code:

import React, { useEffect } from "react";

const FancyButton = React.forwardRef((props, ref) => (
  <button ref={ref}>{props.children}</button>
));

export default function App() {
  const buttonRef = React.createRef();

  useEffect(() => {
    buttonRef.current.focus();
  }, []);

  return (
    <>
      <FancyButton ref={buttonRef}>Click me!</FancyButton>;
    </>
  );
}

In the code above, we have the FancyButton component, which has the button element, which we want to access. To let us access it from App or another component, we call React.forwardRef , which takes a callback with 2 parameters, props and ref .

The props have the props, and the ref is the ref that we can access from the outside. We set the ref prop to the ref parameter so to set the ref to the button.

Then in App , we create the buttonRef and pass it into ref . Then in the useEffect callback, we call buttonRef.current.focus(); to focus the button when App load since we have an empty array as the 2nd argument.

Forwarding refs are also used with 3rd party components. For instance, if we have to use the react-hook-form package and we’re using our own custom input control components, then we have to call forwardRef as follows:

import React from "react";
import { useForm } from "react-hook-form";

const Select = React.forwardRef(({ label }, ref) => (
  <>
    <label>{label}</label>
    <select name={label} ref={ref}>
      <option value="10">10</option>
      <option value="20">20</option>
    </select>
  </>
));

export default function App() {
  const { register, handleSubmit } = useForm();

  const onSubmit = () => {};

  return (
    <>
      <form onSubmit={handleSubmit(onSubmit)}>
        <Select label="Age" ref={register} />
        <input type="submit" />
      </form>
    </>
  );
}

In the code above, we created a custom select control called Select , which is created by calling forwardRef with a callback that takes the ref as the 2nd parameter, we set it as the value of the ref prop in the select element.

Then we can access the ref of select from App .

Conclusion

Forwarding refs means that we are getting the refs from a child component from a parent component.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *