Detect focus lost (focusOut) event in React

avatar
Borislav Hadzhiev

Last updated: Apr 7, 2024
2 min

banner

# Detect focus lost (focusOut) event in React

Use the onBlur prop to detect focus lost (focusOut) event in React.

The onBlur event is triggered when an element is about to lose focus.

App.js
export default function App() { const handleInputBlur = event => { console.log('Input lost focus'); }; const handleDivBlur = event => { console.log('Div lost focus'); }; return ( <div> <div tabIndex={0} onBlur={handleDivBlur}> Hello world </div> <input onBlur={handleInputBlur} /> </div> ); }

react detect focus lost

The code for this article is available on GitHub

React uses the onFocus prop to handle the onfocus event that is triggered when the user sets focus on an element.

Conversely, it uses the onBlur prop to handle the onblur event that is triggered when an element loses focus.

If you need to check if an element is focused in React, click on the following article.

# React doesn't use onFocusIn and onFocusOut

React doesn't use the onFocusIn and onFocusOut events because all React events are normalized to bubble.

App.js
export default function App() { const handleInputBlur = event => { console.log('Input lost focus'); }; const handleDivBlur = event => { console.log('Div lost focus'); }; const handleDivFocus = event => { console.log('Div gained focus'); }; const handleInputFocus = event => { console.log('Input gained focus'); }; return ( <div> <div tabIndex={0} onBlur={handleDivBlur} onFocus={handleDivFocus}> Hello world </div> <input onBlur={handleInputBlur} onFocus={handleInputFocus} /> </div> ); }

react detect focus gained and lost

The code for this article is available on GitHub

Note that some elements, e.g. DIVs are not focusable by default, so in order to handle the focus event on a div, we have to set the tabIndex prop on the element.

App.js
<div tabIndex={0} onBlur={handleDivBlur} onFocus={handleDivFocus}> Hello world </div>
The tabIndex attribute indicates that its element can be focused and where it participates in sequential keyboard navigation (using the Tab key).

When an element's tabIndex is set to 0, the element is focusable in sequential keyboard navigation, after any positive tabIndex values.

You could also set the element's tabIndex to -1, which means that the element is not reachable via sequential keyboard navigation (using the Tab key), but can be focused using JavaScript or by clicking on it with the mouse.

The code for this article is available on GitHub

I've also written an article on how to focus an input when another element is clicked.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.