BOSC
Ways to set focus on an input field after rendering in React

Ways to Set Focus on an Input Field After Rendering in React

There are certain users who use the keyboard with both of their hands for most of their time on their web sessions. They travel webpages, search, close tabs, etc. Whatever they do, they prefer not to shift their hand on the mouse and just comfortably work with resting hands-on keyboard only.

Centralizing these users, we can help them by directly focusing on input fields like the login page’s Email field or the review form’s feedback field.

Table of content

1. Autofocus in HTML

2. Setting up React project

3. Autofocus using React Hooks useRef

4. Autofocus using React class components

5. Conclusion

1. Autofocus in HTML

The autofocus attribute of the HTML <input> tag is a boolean attribute.

The default value of this is false, but if we mention this, it tells the browser to focus on that particular input field, and the user can directly start entering values.

<html>
<body> 
<h1>The autofocus attribute</h1> 
<form>
     <label for="username">Username:</label>
     <input type="text" id="uname" name="uname" autofocus> //Will be focused
     <br><br>
     <label for="email">Email:</label>
     <input type="text" id="email" name="email"> //Won't be focused
</form>
</body>
</html>

Output Result

The Autofocus attribute
The Autofocus attribute

2. Setting up react project

The autofocus we did in HTML can also be done in ReactJS, but before going further, we need to create a React project and look into the project structure to relate with what/where you have to implement in your project to use autofocus.

To create a project, open Command Prompt or PowerShell to the folder where you want to create a project.

Step 1: Create a project of name auto-focus-test

npx create-react-app auto-focus-test

Step 2: Go to created project folder auto-focus-test

cd auto-focus-test

The folder structure will look like:

Folders for setting up a React project
Folders for set a React project

Step 3: Now there is an App.js file inside the src folder. There will be a default React app code; just overwrite that code with the below-given code to create a simple text input field with Email as the label.

import React from 'react';
 
export default function App() {
  return (
    <div className="App">
      <label>Email: </label>
      <input id="name" />
    </div>
  );
}

Email text inpurt fileld
Email text input field

3. Autofocus using React hooks

To focus it when the component renders, we have to use React Hook useEffect, which gets called when particular state variable changes, or we can give an empty array to make sure it renders only once when the component renders.

import React, { useEffect } from 'react';
 
export default function App() {
  useEffect(() => {
    // Instruction we give here will render once component gets rendered
}, []);
 
  return (
    <div className="App">
      <label>Email: </label>
      <input id="name" />
    </div>
  );
}

Now, to point to a particular JSX element, we need to give it a reference with the useRef Hook of React. Here it is ⁢input type=”text” />, an aspect that will be focused on after rendering that page/component.

import { useRef, useEffect } from 'react';
 
export default function App() {
  const inputRef = useRef();
 
  useEffect(() => {
    // Instruction we give here will render once component gets rendered
  }, []);
 
  return (
    <div className="App">
      <label htmlFor="name">Name: </label>
      <input id="name" ref={inputRef} />
    </div>
  );
}

Here, the inputRef is the variable that will store the reference for the ⁢input type=”text” /> element. To access this, we need to use a current keyword like inputRef.current, and as we have to tell React to focus on this, we can just use focus() method inside the useEffect Hook.

import { useRef, useEffect } from 'react';
 
export default function App() {
  const inputRef = useRef();
 
  useEffect(() => {
    inputRef.current.focus();
  }, []);
 
  return (
    <div className="App">
      <label htmlFor="name">Name: </label>
      <input id="name" ref={inputRef} />
    </div>
  );
}

Every time you refresh the page or open it in a new tab, you will notice that the input field will always be focused. The output reference for the same is given below after another method using the class component’s explanation.

Schedule an interview with React developers

4. Autofocus using class component

First, we need to make our App.js file a class component. To do so, just paste the below code inside App.js and save it.

import React, { Component } from "react";
 
class App extends Component {
  render() {
    return (
      <div className="App">
        <label>Email: </label>
        <input id="name" />
      </div>
    );
  }
}
 
export default App;

As we used useEffect in the Functional component, we need to use componentDidMount as an alternative to useEffect for the class component. This will be called once when the component renders.

import React, { Component } from "react";
 
class App extends Component {
  componentDidMount() {
    this.refInput.focus();
  }
 
  render() {
    return (
      <div className="App">
        <label>Email: </label>
        <input id="name" />
      </div>
    );
  }
}
 
export default App;

Now we will give reference to the <input type=”text” /> tag to tell React to get focus on that particular component.

import React, { Component } from "react";
 
class App extends Component {
  componentDidMount() {
    this.refInput.focus();
  }
 
  render() {
    return (
      <div className="App">
        <label>Email: </label>
        <input id="name" 
          ref={(input) => { this.refInput = input; }}
        />
      </div>
    );
  }
}
 
export default App;

Now every time you render with any of the components, whether class or functional App.js, it will look precisely like the below, and directly we can enter a value in the input field:

Final Email Text Input Field
Final Email Text Input Field

5. Conclusion

Here we accomplished focusing on the input field after each render of that component with both the Class and Functional components. If you need a solution for your technical problems in React, hire React experts from Bosc Tech to adopt React development environment. We basically followed the same method in both. We decided on when to focus by useEffect and componentDidMount, and then we gave reference and called focus().

By this, we can give the user smooth surfing on the internet without making them shift their hands from keyboard to mouse and vice versa. This tiny looking change or betterment can impact primary users while surfing.

Thank you for reading. Hope you enjoyed the reading. Please share your thoughts with us. So, we can improve our content.