Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React autofocus input after enabling a disabled input

I'm trying to autofocus a text input (the input is enabled upon selecting a relevant radio option).

The autofocus works when toggling between options that will enable the text input. However, autofocus fails when switching from an option that disables the text input to an option that enables the text input.

  • In the sample link below:

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

    • option 1 is default
    • choose option 3 or option 4
    • input gets enabled
    • autofocus fails (looking for pointer to fix this behaviour)
  • Success case:

    • choose option 3
    • input is enabled
    • switch to option 4
    • input is autoFocussed

sample code for the problem on codesandbox

like image 928
r0hityadav Avatar asked Jul 06 '17 14:07

r0hityadav


2 Answers

This does not work, cause you immediately set it after the setState call, but at this point of lifecycle the component has not re-rendered and the ref to the input is still in a state where it is disabled.

What you need to do is, trigger the focus handling after the component did update in the componentDidUpdate hook.

Something like this (pseudo code)

componentDidUpdate(prevProps, prevState) {

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

It might be possible that you need additional checks like only focus on a transition from disabled to enabled. This could be achieved by doing something like this:

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

Here a link to the updated codesandbox: https://codesandbox.io/s/31RnlkJW4

like image 88
larrydahooster Avatar answered Nov 15 '22 03:11

larrydahooster


Just a little extra to add, autoFocus only works on the initial render of the element (basically only when componentDidMount runs). So that's why it's not automatically focusing when you re-enable the input, it's not being unmounted and then re-mounted. To make autoFocus work, you'd need to move the input and disabled input into separate components and conditionally render them based on state.

like image 40
Chase DeAnda Avatar answered Nov 15 '22 04:11

Chase DeAnda