Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

autofocus in react based on condition if else

How to autofocus for input name based on whether this.props.email exists or not?

if(this.props.email){
    // would like to set autofocus for  <input value={email} name="userName">    
}else{
   // would like to set autofocus for  <input name="password" />
}

 <input value={email} name="userName">             
 <input name="password" />

I was thinking of using refs but is wondering if there is better way to access the name of the input

like image 634
user21 Avatar asked Feb 11 '26 20:02

user21


2 Answers

you may want to try this

<input value={email} autoFocus={this.props.email} name="userName"> 
like image 106
David Vittori Avatar answered Feb 13 '26 18:02

David Vittori


Checkout this Sandbox

This doesn't use if-else, but uses this.props.email, as in your question:

How to autofocus for input name based on whether this.props.email exists or not?


Inside Input.js (component)

<input
  value={this.props.email}
  name="userName"
  autoFocus={this.props.email}
/>
<input name="password" autoFocus={!this.props.email} />

Inside index.js (parent)

<Input email={""} />
like image 44
Kevin Wang Avatar answered Feb 13 '26 17:02

Kevin Wang