user21
user21

Reputation: 1351

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

Upvotes: 3

Views: 4197

Answers (3)

Kevin Wang
Kevin Wang

Reputation: 682

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={""} />

Upvotes: 2

Smarticles101
Smarticles101

Reputation: 1926

You could just use autofocus:

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

Or, with refs:

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

 <input value={email} name="userName" ref={input => {this.emailInput = input}}>             
 <input name="password" ref={input => {this.passwordInput = input}} />

Upvotes: 1

David Vittori
David Vittori

Reputation: 1196

you may want to try this

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

Upvotes: 4

Related Questions