-1

I am trying to set the focus on my React page but it doesn't work because the component updates which I think overrides the componentDidUpdate.

is there another way to do this?

this is the code I normally use to focus

document.querySelector("#input-box").focus();
Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
paulza3335
  • 13
  • 1
  • 6

1 Answers1

1

If you are using react you should ideally be using refs and using them to set focus. Check the accepted answer for Set focus on input after render

If you have a problem of the component losing focus a lot, this can happen if the key value that you set for the component is not unique. React uses the key value that you set to track components across render cycles. If the key is generated incorrectly then you can have a scenario where the component loses focus across render cycles. For e.g., a controlled input box when a user is typing in it.

trance
  • 128
  • 1
  • 8