How to focus on a input element in React (after render)
In this tutorial, we are going to learn about how to focus on 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 access the input
element reference by using react callback refs.
Next, we invoked this.searchInput.focus()
method inside componentDidMount()
, so that the input element is focussed.
Set focus using hooks
In the above example, we have use class-based react components let’s see in hooks version.
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>
);
}
Set 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>
);
}