0

I have a component with input, is there any way to focus using the name?

<div onClick={this.handleClick.bind(this)}>
    ... Some more code ...
        <input type="text" name={this.props.name} onChange={this.props.onChange} autoFocus/>
    ... Some more code ...
</div>

On click of the parent div, I have a on click event attached to it.

handleClick(e) {
    // Need to focus may be using refs, but not sure how to do it.
    return this.props.onClick(this.props.name);
}
1
  • you should be able to do auto focus using input autoFocus property. But if you have multiple text box and all need to focus during loading last one will win Commented Jan 3, 2017 at 6:58

1 Answer 1

1

Component:

<div onClick={this.handleClick.bind(this)}>
    ... Some more code ...
        <input type="text" ref={(input) => { this.input = input; }} name={this.props.name} onChange={this.props.onChange} autoFocus/>
    ... Some more code ...
</div>

Click handler:

handleClick(e) {
    this.input.focus();
    return this.props.onClick(this.props.name);
}

or

Component:

<div onClick={this.handleClick.bind(this)}>
    ... Some more code ...
        <input type="text" ref={this.props.name} name={this.props.name} onChange={this.props.onChange} autoFocus/>
    ... Some more code ...
</div>

Click Handler:

handleClick(e) {
    this.refs[this.props.name].focus();
    return this.props.onClick(this.props.name);
}
Sign up to request clarification or add additional context in comments.

12 Comments

I think in the second method, this would refer to the div rather than the input. Tried both but no luck.
Are you getting some error message? Have you tried to add logs with this.refs inside componentDidMount to check if refs are defined?
I do not see any error, and I'm not sure how to log this,refs inside componenetDidMount Does this work for testing? componentDidMount(){ console.log(this.props.name); }
I see the refs are not being rendered <input type="text" name="pets" placeholder="NO INFO FOUND" data-reactid=".0.2.0.5.0.1.$0.0.1.1">
ref is an attribute of the virtual DOM, it doesn't appear on the "real" DOM.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.