简体   繁体   中英

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:

  • Most articles speak to how to focus controls when a component is first mounted, but I want to do this after setState is called.
  • Other articles speak of how to do it using references, notably createRef and Ref callbacks . I tried both and neither seem to work and I suspect that this is because those are use cases where setState is not called, so the component is not rerendered - it's merely a button or action causing a different element to get focussed upon the same "render"...
  • There are also some articles that speak of using autofocus , but this seems to do nothing in my case.

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

  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])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM