Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
May 11, 2022 06:55 am GMT

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 pages Email field or the review forms 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 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:

Image description

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:

Image description

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>  );}

Image description

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 components explanation.

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 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:

Image description

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.


Original Link: https://dev.to/kuldeeptarapara/ways-to-set-focus-on-an-input-field-after-rendering-in-react-1894

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To