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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *