Geno Diaz
Geno Diaz

Reputation: 510

React focus on child component input

I currently implement Redux-Form in order to add InputFields to my application. Is there are way to manually focus on an input of a child component?

Code for adding child component:

<Field name="Quantity" ref="quantity" onKeyPress={(event) => this.handleKeyPress('inventory', event)} component={ InputField }/>

Code for child component:

render() {
    const { input } = this.props;
    const inputClass = classNames({ 'parsley-error': this.props.meta.touched && this.props.meta.error }, 'form-control')
return (
    <div>
        {this.props.meta.touched && this.props.meta.error && <span className="parsley-error-message">{this.props.meta.error}</span>}
        <Input {...input} className={inputClass} onKeyPress={this.props.onKeyPress} standalone type="text" placeholder={this.props.placeholder}/>
    </div>
   )
}

Current implementation attempt at focus:

handleKeyPress(value, event){
  if(event.charCode == 13){
    this.refs["inventory"].getDOMNode().focus();
  }
}

I hard coded to focus inventory just for test purposes

Upvotes: 2

Views: 926

Answers (1)

Tim McIntire
Tim McIntire

Reputation: 83

Inside your Input component you should be able to do:

`<input type="text" autoFocus />` 

Note the F has to be capitalized. I haven't test this on newly generated components but in theory it should work.

Upvotes: 1

Related Questions