DEV Community

Joseph Mawa
Joseph Mawa

Posted on

What is forwarding ref and how do you use it?

Before reading this article, it is very important to familiarize yourself with useRef hook and createRef API. This has been covered in my earlier article useRef hook and createRef API.

Ref forwarding is a technique for automatically passing ref from a component to one of its children. According to React documentation, this might not be necessary in most applications but might be useful for some kinds of components, especially in reusable component libraries.

In the example below App renders Form component.

export default function App() {
  const myRef = useRef();
  return (
    <div className="App">
       < Form ref = {myRef} />
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

If you want to reference a DOM element or a class component rendered by Form from App, you can pass a ref to Form component. Form is wrapped in forwardRef so that it passes or forwards the ref to a DOM element or class component it renders.

function Form(props, ref) {
  return (
    <form>
      <input type="text" placeholder="Name" />
      <input type="submit" ref={ref} />
    </form>
  );
}

export default React.forwardRef(Form);

Enter fullscreen mode Exit fullscreen mode

Form takes two parameters. The first parameter is props and the second is ref passed to it from its parent Component App. It then forwards the ref to either a DOM element or a class component it renders which in the example above is the input element. Take note of how Form has been wrapped in forwardRef. The second parameter to Form, ref, only exists if you wrap it inside forwardRefand ref JSX attribute has been passed to it from its parent component. The above example can also be written as:

export default React.forwardRef(function Form(props, ref) {
  return (
    <form>
      <input type="text" placeholder="Name" />
      <input type="submit" ref={ref} />
    </form>
  );
});

Enter fullscreen mode Exit fullscreen mode

The parent component App then references<input type="submit" /> via myRef's current property.

That is a brief summary of how forwardRef is used.

Thanks for reading this article till the end. If you find anything technically inaccurate, please leave a comment below. You can also share it on twitter if you find it useful. Someone might find it useful too.

Reference

React documentation

Top comments (0)