Last updated: Apr 7, 2024
Reading time·2 min
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.
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 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.
onFocusIn
and onFocusOut
React doesn't use the onFocusIn
and onFocusOut
events because all React
events are normalized to bubble.
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> ); }
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.
<div tabIndex={0} onBlur={handleDivBlur} onFocus={handleDivFocus}> Hello world </div>
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.
I've also written an article on how to focus an input when another element is clicked.