Autofocus signal input after enabling disabled input

I am trying to autofocus a text input (the input is activated when the corresponding radio option is selected).

Autofocus works when switching between options that will allow you to enter text. However, autofocus does not work when switching from an option that disables text input to an option that allows text input.

  • In the link below:

    • option 1, option 2: disable text input
    • option 3, option 4: enable text input
  • Failure case:

    • option 1 by default
    • choose option 3 or option 4
    • the input is activated.
    • autofocus error (looking for pointer to fix this behavior)
  • Success case:

    • select option 3
    • included.
    • go to option 4
    • autofocus input

example code for codeandbox problem

+3


source to share


2 answers


This doesn't work because you immediately set it after calling setState, but at this point in the lifecycle, the component is not redrawn and the input reference is still in a disabled state.

What you need to do is invoke focus handling after the component has updated in hook.doc.ddUpdate.

Something like this (pseudocode)

componentDidUpdate(prevProps, prevState) {

  if (this.state.enabled) {
     this.inputValue.focus();
  }
}

      



You may need additional checks, such as focus on going from disabled to enabled. This can be achieved by doing something like this:

componentDidUpdate(prevProps, prevState) {
  if (!prevState.enabled && this.state.enabled) {
    this.inputValue.focus();
  }}

      

Here's a link to updated codes and: https://codesandbox.io/s/31RnlkJW4

+2


source


It's enough to add a little, autoFocus

it only works with the initial rendering of the element (mostly only at startup componentDidMount

). So why doesn't it automatically focus when re-enabling input, it doesn't unmount and then mount again. To get the job done autoFocus

, you will need to move the input and disable input to individual components and conditionally render them based on state.



+1


source







All Articles