Thursday, November 28, 2024
Google search engine
HomeLanguagesJavascriptHow to set focus on an input field after rendering in ReactJS...

How to set focus on an input field after rendering in ReactJS ?

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:

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments