Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

reactjs

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.

like image 384
thando Avatar asked Jun 28 '16 08:06

thando


Video Answer


2 Answers

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!

like image 75
schu34 Avatar answered Sep 29 '22 11:09

schu34


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();
like image 40
user3859895 Avatar answered Sep 29 '22 11:09

user3859895