Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React focus input for Modal/Dialog

Tags:

reactjs

I am using React 14 and ES6/7. I have a modal Dialog that has a couple of inputs and when it opens, I want to focus on the first input. The dialog opens and closes fine and it's open property is toggled as expected (that code omitted for brevity below and because it's not really relevant) .

I've tried autoFocus and componentDidUpdate and there are no console errors but nothing seems to give the input focus. What am I missing? I would expect componentDidUpdate to work, but it does not ...

Dialog.jsx:

...

componentDidUpdate(nextProps){
  console.log(this.props)
  if(this.props.open) { //<-THIS IS TRUE AT THIS TIME!!!
    this.refs.emailInput.focus(); //<-NO ERRORS HERE OR AT ALL, BUT NO FOCUS EITHER
  }
}

...
render() {
  return (
    <form onSubmit={this.props.submitLogin} noValidate>
      <Dialog {...this.props}
        key="loginDialog"
        title="Login" actions={loginActions}>
        <input 
           ref="emailInput"
           key="emailField"
           placeholder="Email"
           type="email"
           autoFocus
        />
        <input
          key="passwordField"
          placeholder="Password"
          type="password"
        />
      </Dialog>
    </form>
  )
}

...

TIA!

like image 849
D Durham Avatar asked Dec 06 '25 18:12

D Durham


1 Answers

Turns out this was a bug in the components from Material UI that they since recently fixed.

like image 159
D Durham Avatar answered Dec 08 '25 09:12

D Durham



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!