dominik dominik - 1 year ago 184
React JSX Question

ReactJS: How-to set focus to input-element when it enters the DOM?

How to set focus to an

input
element when it enters the DOM?

Scenario



When a button is clicked the input element is displayed. How to set the focus to this element?

Code-Snippet



class Component extends React.Component{
constructor(props) {
super(props);
this.state = {
showInput: false
}
}

render() {
return (
<div>
<div onClick={() => {
this.setState({showInput: true});
ReactDOM.findDOMNode(this.refs.myInput).focus() // <- NOT WORKING
}}>
Show Input
</div>
{
(this.state.showInput) ? (
<input
type="text"
ref="myInput"
/>
) : ""
}
</div>
);
}
}


Calling
ReactDOM.findDOMNode(this.refs.myInput).focus()
after state change does not work. Also changing just the
style
or
type
property on state change does not work.

Answer Source

In the componentDidMount and componentDidUpdate hooks do this:

ReactDOM.findDOMNode(this.refs.myInput).focus()
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download