33
Understanding the use of useRef hook & forwardRef in React
The useRef hook in react is used to create a reference to an HTML element. Most widely used scenario is when we have form elements and we need to reference these form elements to either print their value or focus these elements etc.
So the {useRef} hook is imported from "react" like other react hooks and we use them inside functional components to create references and this can be assigned to an html element in the jsx by using the "ref" attribute.
An example for using the useRef hook is shown below-
import React, { useEffect, useRef } from "react";
const UseRefHookExplained = (props) => {
// Creating refs for username and password
const userNameRef = useRef(null);
const passwordRef = useRef(null);
// We are also creating a reference to the Login button
const submitBtnRef = useRef(null);
// useEffect to set the initial focus to the user name input
useEffect(() => {
userNameRef.current.focus();
}, []);
// This function is used to handle the key press.
// Whenever user hits enter it moves to the next element
const handleKeyPress = (e, inputType) => {
if (e.key === "Enter") {
switch (inputType) {
// Checks if Enter pressed from the username field?
case "username":
// Moves the focus to the password input field
passwordRef.current.focus();
break;
// Checks if Enter pressed from the password field?
case "password":
// Moves the focus to the submit button
submitBtnRef.current.focus();
e.preventDefault();
break;
default:
break;
}
}
};
// Function to handle the submit click from the button
const handleSubmit = () => {
alert("submitted");
};
// getting the style as prop from the parent.
// Basic style to center the element and apply a bg color
const { style } = props;
return (
<div style={style}>
<h2>Example for using useRef Hook</h2>
<h3>Login</h3>
<input
type="text"
name="username"
ref={userNameRef}
onKeyDown={(e) => handleKeyPress(e, "username")}
/>
<input
type="password"
name="password"
ref={passwordRef}
onKeyDown={(e) => handleKeyPress(e, "password")}
/>
<button ref={submitBtnRef} onClick={handleSubmit}>
Login
</button>
</div>
);
};
export default UseRefHookExplained;
So the concept of useRef hook is straight forward as you can see in the above code. Follow the following steps -
- We import useRef hook from react
- We initialize this hook (eg: const inputRef = useRef(null))
- The reference created is attached to an html element using the "ref" attribute.
Now we will have a reference to this element readily available to be used to make changes like getting the value, focusing etc
Focus state moving to the button after entering the password and clicking on Enter
So, this much should be pretty clear by now. Now let us look at a scenario when we will be using another React component for input.
In this case it becomes a little difficult to pass on the reference that we have defined in the parent component as a property to the child (Input component).
React provides us a way to handle this scenario and forward the refs to the child component using React.forwardRef
Let us check the example code to see the changes -
( I have added a comment "//new" to identify the newly added lines)
import React, { useEffect, useRef } from "react";
import Input from "./Input"; // new
const UseRefHookExplained = (props) => {
// Creating refs for username and password
const userNameRef = useRef(null);
const passwordRef = useRef(null);
// We are also creating a reference to the Login button
const submitBtnRef = useRef(null);
// useEffect to set the initial focus to the user name input
useEffect(() => {
userNameRef.current.focus();
}, []);
// This function is used to handle the key press.
// Whenever user hits enter it moves to the next element
const handleKeyPress = (e, inputType) => {
if (e.key === "Enter") {
switch (inputType) {
// Checks if Enter pressed from the username field?
case "username":
// Moves the focus to the password input field
passwordRef.current.focus();
break;
// Checks if Enter pressed from the password field?
case "password":
// Moves the focus to the submit button
submitBtnRef.current.focus();
e.preventDefault();
break;
default:
break;
}
}
};
// Function to handle the submit click from the button
const handleSubmit = () => {
alert("submitted");
};
// getting the style as prop from the parent.
// Basic style to center the element and apply a bg color
const { style } = props;
return (
<div style={style}>
<h2>Example for using useRef Hook</h2>
<h3>Login</h3>
{/* New. Using the Component instead of input element */}
<Input
type="text"
name="username"
ref={userNameRef}
onKeyDown={(e) => handleKeyPress(e, "username")}
/>
{/* New. Using the Component instead of input element */}
<Input
type="password"
name="password"
ref={passwordRef}
onKeyDown={(e) => handleKeyPress(e, "password")}
/>
<button ref={submitBtnRef} onClick={handleSubmit}>
Login
</button>
</div>
);
};
export default UseRefHookExplained;
Now let us look at the Input.js component
import React from "react";
/* In the functional component, a second argument
is passed called ref, which will have access to
the refs being forwarded from the parent */
const Input = (props, ref) => {
/* assigning the ref attribute in input and spreading
the other props which will contain type, name, onkeydown etc */
return <input {...props} ref={ref} />;
};
// wrapping the Input component with forwardRef
const forwardedRef = React.forwardRef(Input);
// Exporting the wrapped component
export default forwardedRef;
So, React.forwardRed provides us a way with which we can still pass on or forward the refs defined in the parent component to the child component.
Hope you learned something new today!
33