Today I Learned

hashrocket A Hashrocket project

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 SyntheticEvents 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.

See More #react TILs
Looking for help? At Hashrocket, our JavaScript experts launch scalable, performant apps on the Web, Android and iOS. Contact us and find out how we can help you.