Skip to content
Related Articles

Related Articles

How to set focus on an input field after rendering in ReactJS ?
  • Last Updated : 05 Jan, 2021

Setting focus on an input field after rendering in ReactJS can be done in the following ways, but before doing that, set up your project structure with the following steps:

Creating React Application:

Step 1: Create a React application using the following command:

npx create-react-app foldername

Step 2: After creating your project folder i.e. foldername, move to it using the following command:

cd foldername

Project Structure: It will look like the following.



Project Structure

Approach 1: we can do it in componentDidMount() function and refs callback. For example:

componentDidMount() {
  this.nameInput.focus();
}

Filename: App.js

Javascript




import React, { Component } from "react";
class App extends Component {
  
  componentDidMount() {
    this.nameInput.focus();
  }
  
  render() {
    return (
      <div>
        <input
          defaultValue="It Won't focus"
        />
        <input
          ref={(input) => { this.nameInput = input; }}
          defaultValue="It will focus"
        />
      </div>
    );
  }
  
}
  
export default App;

Approach 2: If we just want to focus on an element when it mounts (initially renders) a simple use of the autoFocus attribute will do. we can use the autoFocus prop to have an input automatically focus when mounted. 

Filename: App.js

Javascript




import React, { Component } from "react";
  
class App extends Component  {
    
  render() {
    return(
    <div>
      <input 
        defaultValue="It Won't focus" 
      />
      <input autoFocus
        defaultValue="It will focus"
      />
    </div>
    );
  }          
}
  
export default App;

Approach 3: We can use the below syntax using the inline ref property.

<input ref={input => input && input.focus()}/>

Filename: App.js

Javascript




import React, { Component } from "react";
  
class App extends Component  {
    
  render() {
    return(
      <div>
        <input 
          defaultValue="It Won't focus" 
        />
        <input 
          ref={(input) => {input && input.focus() }} 
          defaultValue="It will focus"
        />
      </div>
    );
  }
            
}
  
export default App;

Step to Run Application: Run the application using the following command from the root directory of the project:

npm start

Output:

react-js-img

My Personal Notes arrow_drop_up
Recommended Articles
Page :