3

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

user21
  • 1,261
  • 5
  • 20
  • 41

3 Answers3

4

you may want to try this

<input value={email} autoFocus={this.props.email} name="userName"> 
David Vittori
  • 1,146
  • 1
  • 13
  • 30
  • 1
    Isn't it better to use !!this.props.email ? – Bruno Mazzardo Jan 22 '19 at 19:25
  • what does !!this.props.email means? is it same as {this.props.email}? – user21 Jan 22 '19 at 19:36
  • both {this.props.email} and {!!this.props.email} works but I was wondering what is the difference between {this.props.email} and {{!!this.props.email}}? {{!!this,props.email}} works for email is undefined case but not {this.props.email}}? – user21 Jan 22 '19 at 19:45
  • Sorry for the delay, but that's right, !!this.props.email cover undefined case, it may don't matter here, but overall it's better to use for safety. – Bruno Mazzardo Jan 23 '19 at 12:58
2

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={""} />
Kevin Wang
  • 644
  • 1
  • 8
  • 20
1

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}} />
Smarticles101
  • 1,822
  • 1
  • 14
  • 28