Reputation: 483
How to set focus to an input
element when it enters the DOM?
When a button is clicked the input element is displayed. How to set the focus to this element?
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.
Upvotes: 10
Views: 23497
Reputation: 11
I had to define the variable as HTMLInputElement
1st...
private inputSearch: HTMLInputElement;
And then add this into the control:
ref={(input) => { this.inputSearch = input; }}
THEN I could get this to build/work:
this.inputSearch.focus();
Upvotes: 1
Reputation: 985
Assuming you only need one visible input on the page at a time to have autofocus Poh Zi How's suggestion of using the autofocus
is probably the simplest.
<input type="text" autofocus/>
should do the trick, no JS needed!
Upvotes: 10
Reputation: 131
From the docs:
"findDOMNode only works on mounted components (that is, components that have been placed in the DOM). If you try to call this on a component that has not been mounted yet (like calling findDOMNode() in render() on a component that has yet to be created) an exception will be thrown."
As mentioned by Piyush.kapoor, you need to place that incomponentDidMount
and/or componentDidUpdate
.
Upvotes: 0
Reputation: 6459
you should use ref
<input ref={(input) => { this.inputSearch = input; }} defaultValue="search ... " />
and use this code for focus
this.inputSearch.focus();
Upvotes: 4
Reputation: 6803
In the componentDidMount
and componentDidUpdate
hooks do this:
ReactDOM.findDOMNode(this.refs.myInput).focus()
Upvotes: 9