loading...

What is forwarding ref and how do you use it?

nibble profile image Joseph Mawa ・2 min read

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>
  );
}

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);

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>
  );
});

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

Posted on by:

nibble profile

Joseph Mawa

@nibble

Programming noob. Learning MERN stack.

Discussion

markdown guide