Remove the focus from a button on click in React

Remove the focus from a button on click in React

In this post we will give you information about Remove the focus from a button on click in React. Hear we will give you detail about Remove the focus from a button on click in ReactAnd how to use it also give you demo for it if it is necessary.

we are going to learn about how to remove the focus from a button element on click in React.

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

import React from "react";function App() {  return (    <div>      <button>Search</button>    </div>  );}

Now, when a user clicks on the button we need to remove the focus of it.

Removing the focus from a button on click

To remove the focus from a button on click, first we need to access the button inside the react component using the useRef hook then call a blur() method on it. So, it removes the focus of a button.

Here is an example:

import React, {useRef} from "react";function App() {   const buttonRef = useRef(null)   function handleClick(){    buttonRef.current.blur(); // removing focus  }  return (    <div>      <button onClick={handleClick} ref={buttonRef}>         Search      </button>    </div>  );}

In the example above, we first added a buttonRef to the button element. So, it allows us to access and modify the dom node of an button inside the component methods.

Next, we added a buttonRef.current.blur() method inside the handleClick() event handler, so when a Search button is clicked it removes the focus from a button.

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 button, then call a focus() method on it.

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

Hope this code and post will helped you for implement Remove the focus from a button on click 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

For More Info See :: laravel And github

We're accepting well-written guest posts and this is a great opportunity to collaborate : Contact US