How to set a focus to a input element in React
In this tutorial, 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>
);
}