Categories
React Answers

How to use useref hook in React?

Spread the love

To use the useRef hook in React, we call it in our component to return a ref.

Then we can assign that to an element.

For instance, we write

function TextInputWithFocusButton() {
  const inputEl = useRef(null);

  const onButtonClick = () => {
    inputEl.current.focus();
  };
  return (
    <>
      <input ref={inputEl} type="text" />
      <button onClick={onButtonClick}>Focus the input</button>
    </>
  );
}

to set the input’s ref prop to the inputEl ref which we created with useRef.

Then we can access the input with inputEl.current.

And we call focus on it to focus on the input.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.