React SyntheticEvent for Focus and Blur
Some JavaScript events like focus
and blur
do not bubble to parent elements. Let's say that we have:
<div
onfocus="console.log('div focus')"
onblur="console.log('div blur')"
>
<input
type="text"
placeholder="Type something here"
onfocus="console.log('input focus')"
onblur="console.log('input blur')"
>
</div>
Then if we focus we'll see in the console input focus
and if we blur we'll see input blur
. This makes a lot of sense as a div
does not have the concept to focus, there's no blinking cursor or anything like that.
But in React the scenario is different. In an attempt to standardize all browser events to behave similarly to each other and across different browsers, React wraps all events in SyntheticEvent
s and for the onFocus
and onBlur
events we'll see that they do bubble up:
<div
onFocus={() => console.log('div focus')}
onBlur={() => console.log('div blur')}
>
<input
type="text"
placeholder="Type something here"
onFocus={() => console.log('input focus')}
onBlur={() => console.log('input blur')}
/>
</div>
Here if we focus we'll see input focus
and div focus
in this order and if we blur we'll see input blur
and div blur
in this order again.