levraininjaneer
levraininjaneer

Reputation: 1377

How to focus an element after re-render with ReactJS

In my web-app, a user can save the current record by pressing enter. A message is then shown showing "record successfully saved".

Since the blinking cursor in one of the input boxes detracts from the "the record is now saved" impression, I'd like the application to focus a particular control at this point, like a "Back" button, for example.

How can I get React to set focus to an element during a re-render? If I use a someCreatedRef.current.focus() command, should that be before or after the setState command?

I've tried everything I can find in documentation about focusing elements, and none of it works for me:

Edit: Thanks to Ganesh Krishna, I could crack this. Here is a code Sandbox of this solution.

Upvotes: 1

Views: 4082

Answers (1)

Ganesh Krishna
Ganesh Krishna

Reputation: 714

  1. If I use a someCreatedRef.current.focus() command, should that be before or after the setState command?

    There is no such order.

  2. but I want to do this after setState is called.

    If you want to execute certain changes after setState is called you can do the following.

If you are using class component: setState method provides a callback function that can be executed after state change has been made.

this.setState({
    // set the state variable 
},() => {
    // add the code to focus on particular element.
});

If you are using hooks: Just add useEffect hook and add the state variable after which is set, you want to focus, as a dependency

useEffect(() => {
 // add the code to focus on particular element.
}, [stateVariable])

Upvotes: 1

Related Questions