1 / 22

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

Here is the complete article on how you can set a focus on the input field after rendering in React. Learn autofocus using React hooks & class components in this article.

John115
Download Presentation

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

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 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.

  2. Table of content 1. Autofocus in HTML 2. Setting up 3. Autofocus using React hooks useRef 4. Autofocus Using React class components 5. Conclusion

  3. 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.

  4. <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>

  5. Output Result:

  6. 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.

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

  8. The folder structure will look like:

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

  10. You will get output like below:

  11. 3. Autofocus using React hooks To focus it when the component renders, we have to use React HookuseEffect, 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.

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

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

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

  15. 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.

  16. 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;

  17. 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; 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.

  18. 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 we will give reference to the <input type=”text” /> tag to tell React to get focus on that particular component.

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

  20. 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().

  21. 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. Content Resource: https://bosctechlabs.com/set-focus-on-input-field-after-rendering-react/

More Related