How to use React forwardRef

renatobentorocha

Renato Rocha

Posted on January 30, 2020

How to use React forwardRef

When we are creating a React application, some times, we need access properties of a Element created through jsx. As an example, a simple case where we want to set focus on a input text. In this case we can do that using the React hook useRef in a straight away.



import React, { useRef, useEffect } from "react";

function App() {
  const inputRef = useRef(null);

  useEffect(() => {
    inputRef.current.focus();
    console.log({ inputRef });

    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  return (
    <div>
      <input type="text" ref={inputRef} style={style} />
    </div>
  );
}

export default App;


Enter fullscreen mode Exit fullscreen mode

The useRef hook returns an object that contains a reference to the corresponding DOM node whenever that node changes.

However, what if we are using a pretty cool Input Component from a third party and go along with the same way, using the useRef hook?



import React from "react";

const Input = () => <input type="text" style={style} />;

export default Input;


Enter fullscreen mode Exit fullscreen mode


import React, { useRef, useEffect } from "react";
import Input from "./Input";

function App() {
  const inputRef = useRef(null);

  useEffect(() => {
    if (inputRef.current) {
      inputRef.current.focus();
    }

    console.log({ inputRef });

    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  return (
    <div>
      <Input ref={inputRef} />
    </div>
  );
}

export default App;


Enter fullscreen mode Exit fullscreen mode

So we will receive the warning message and also can see that the reference to Input Component is null:

In this case, the error was because the Input Component is a children of App component and the "ref" cannot pass from App Component to Input. On this case, we need to change the Input Component to use the forwardRef.



import React, { forwardRef } from "react";

const Input = (props, ref) => <input ref={ref} type="text" style={style} />;

export default forwardRef(Input);


Enter fullscreen mode Exit fullscreen mode

And another example where we may need to use forwardRef is in conjunction with the High Order components.

💖 💪 🙅 🚩
renatobentorocha
Renato Rocha

Posted on January 30, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related