by Sai gowtham

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.

google search input focus

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.

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

input element is focussed in react app

Set focus using hooks

In the above example, we have use class-based react components let’s see in hooks version.

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

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
45,614 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
284,472 students enrolled
40 hours of video content
View Course
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
130,921 students enrolled
48.5 hours of video content
View Course