How to use React forwardRef
Renato Rocha
Posted on January 30, 2020
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;
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;
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;
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);
And another example where we may need to use forwardRef is in conjunction with the High Order components.
Posted on January 30, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.