Borislav Hadzhiev
Sun May 01 2022·2 min read
Photo by Marcos Paulo Prado
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.
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.
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.
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.