Categories
React

How to Focus Something on Next Render with React Hooks?

Spread the love

We may want to focus something on the next render within a component created with React hooks.

In this article, we’ll look at how to focus on an element on the next render within a component created with React hooks.

Focus Something on Next Render with React Hooks

To focus on an element on the next render, we can write something like the following:

import { useEffect, useRef, useState } from "react";

export default function App() {
  const [isEditing, setEditing] = useState(false);
  const toggleEditing = () => {
    setEditing(!isEditing);
  };

  const inputRef = useRef(null);

  useEffect(() => {
    if (isEditing) {
      inputRef.current.focus();
    }
  }, [isEditing]);

  return (
    <div>
      {isEditing && <input ref={inputRef} />}
      <button onClick={toggleEditing}>edit</button>
    </div>
  );
}

We create the isEditing state with the useState hook.

It’s set to false initially.

Next, we add the toggleEditing function to call setEditing function to the negated value of the isEditing state.

Then we create the inputRef ref that lets us assign to the input element below.

Next, we have the useEffect hook that runs when the isEditing state is changed.

We check the isEditing value, and if it’s true , we call inputRef.current.focus() to focus on the input.

The 2nd argument is set to [isEditing] so that isEditing ‘s value is watched.

Then we render the input if isEditing is true .

And in the input, we assigned a ref to it.

And we have a button that runs the toggleEditing function when we click on edit.

Conclusion

We can focus on an element on next render easily by watching a state’s value with useEffect .

Then we can check the value of the state and call focus on the element object, which is the ref which we assigned to the element.

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 *