r0hityadav
r0hityadav

Reputation: 83

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.

sample code for the problem on codesandbox

Upvotes: 7

Views: 8177

Answers (2)

larrydahooster
larrydahooster

Reputation: 4163

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

Upvotes: 7

Chase DeAnda
Chase DeAnda

Reputation: 16451

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.

Upvotes: 4

Related Questions