Detect focus lost (focusOut) event in React

avatar

Borislav Hadzhiev

Last updated: May 1, 2022

banner

Photo from Unsplash

Detect focus lost (focusOut) event in React #

Use the onBlur prop to detect focus lost (focusOut) event in React, e.g. <input onBlur={handleInputBlur} />. 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

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.

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

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.

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 with JavaScript or by clicking on it with the mouse.

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.