by @saigowthamr

React Set focus on the input field after render

Home » react » React Set focus on the input field after render

In this example, you will learn how to set a focus to the input field after the component is rendered.

import React,{Component} from 'react';

class App extends Component{
  componentDidMount(){
    this.nameInput.focus();  }
  render() {
    return(
      <div>
        <input
          ref={(inputEl) => this.nameInput = inputEl}        />
      </div>
    );
  }
}

In the above code, we have used callback refs to access the input element and componentDidmount() lifecycle method is used to set the focus to the input field after render.