by Sai gowtham

React - remove the focus from a input element

In this tutorial, we are going to learn about how to remove the focus from a input element in React.

Consider, we have the following component in our React app.

import React, { useEffect, useRef } from "react";

function App() {
  const searchInput = useRef(null)

  return (
    <div>
      <label>Search </label>
      <input ref={searchInput}  autofocus/>
      <button>Remove focus</button>
    </div>
  );
}

Now, we need to remove the focus from the above input element.

Removing the focus from a input

To remove the focus from a input element in React, first we need to access the element inside the component using ref then call a blur() method on it.

Here is an example:

import React, { useEffect, useRef } from "react";

function App() {
  const searchInput = useRef(null);

   function handleFocus(){
    searchInput.current.blur(); // removing focus
  }

  return (
    <div>
      <label>Search </label>
      <input ref={searchInput}  autofocus/>
      <button onClick={handleFocus}>Remove focus</button>    </div>
  );
}

In the example above, we first added a searchInput ref to the input element. So, we can access and modify the dom node of an input element inside the component methods.

Next, we added a searchInput.current.blur() method inside the handleFocus() event handler, so when a Remove focus button is clicked it removes the focus from a input element.

We used the HTMLElement.blur() to remove the focus from a element.

The blur() method removes the keyboard focus from the element, where it was called on.

If you want to set a focus back to the input element, then call a focus() method on the input element.

searchInput.current.focus(); // adding the focus

Css Tutorials & Demos

How rotate an image continuously in CSS

In this demo, we are going to learn about how to rotate an image continuously using the css animations.

How to create a Instagram login Page

In this demo, i will show you how to create a instagram login page using html and css.

How to create a pulse animation in CSS

In this demo, i will show you how to create a pulse animation using css.

Creating a snowfall animation using css and JavaScript

In this demo, i will show you how to create a snow fall animation using css and JavaScript.

Top Udemy Courses

JavaScript - The Complete Guide 2022 (Beginner + Advanced)
JavaScript - The Complete Guide 2022 (Beginner + Advanced)
116,648 students enrolled
52 hours of video content
$14.99 FROM UDEMY
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
631,582 students enrolled
49 hours of video content
$24.99 FROM UDEMY
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
203,937 students enrolled
31.5 hours of video content
$14.99 FROM UDEMY