How to set a focus to a input element in React
In this post we will give you information about How to set a focus to a input element in React. Hear we will give you detail about How to set a focus to a input element in ReactAnd how to use it also give you demo for it if it is necessary.
we are going to learn about how to set a focus to a input element when a component is rendered into the dom.
If we open a Google.com the input element is focused automatically and we can start typing without any button click.
Let’s learn how we can do it in react apps.
In react, we have the ComponentDidMount() lifecycle method where it runs when a component is mounted to the dom tree.
The ComponentDidMount() method is the best place to set a focus on the input element.
Let’s see an example:
import React,{Component} from 'react';class App extends Component { componentDidMount() { this.searchInput.focus(); } render() { return ( <div> <label>Search </label> <input ref={inputEl => (this.searchInput = inputEl)} /> </div> ); }}
In the above code first, we accessed the input element reference by using the react callback refs.
Next, we invoked this.searchInput.focus() method inside the componentDidMount(), so when a component is rendered to the dom it add a focus to the input element.
Setting focus using hooks
In the above example, we have use class-based react components. let’s see how can we set a focus to the input element using the react hooks.
import React, { useEffect, useRef } from "react";function App() { const searchInput = useRef(null); useEffect(()=>{ // current property is refered to input element searchInput.current.focus(); },[]) return ( <div> <label>Search </label> <input ref={searchInput} /> </div> );}
Setting the focus on button click
import React, { useEffect, useRef } from "react";function App() { const searchInput = useRef(null) function handleFocus(){ searchInput.current.focus() } return ( <div> <label>Search </label> <input ref={searchInput} /> <button onClick={handleFocus}>Set focus</button> </div> );}
Hope this code and post will helped you for implement How to set a focus to a input element in React. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs