...

/

Testing the useRef Hook

Testing the useRef Hook

Learn how React allows direct DOM manipulation and supports parent-child interaction.

Using useRef to control DOM elements

There's always a chance that React runs short in terms of controlling the internals of a DOM element. Let's say there's an input and a button, as in the image below, Upon a button click, we want to manually focus on the input:

Press + to interact
Focus input
Focus input

Normally, if we click the button, it gets focused, and if we click somewhere else, it loses focus. But in this case, after we click the "Focus" button, we want to focus the input instead of the button so that the user can type right away.

Let's see how we can apply useRef to make this happen:

const Title = () => {
// Ref to store a reference to the input element
const ref = useRef();
// Function to handle button click and focus on the input element
const onClick = () => {
ref.current.focus();
};
// JSX structure with an input element and a button to trigger focus
return (
<>
<input ref={ref} />
<button onClick={onClick}>focus</button>
</>
);
}
Using a ref to focus on an input element when a button is clicked

In the preceding example, after input is mounted, its instance is stored in ref.current. When we click the button, the event handler uses the ref to invoke a native DOM focus method to make the input focused. That's it! ...