Skip to content
Advertisement

React: Fire a function when the element is blurred

I’m trying to fire a function when an element has loses focus, but it appears the blur event is not being recognized in my React app. I’m unclear on what I’m missing. The following snippet is just above the return method within my component.

My div carries the ref {infoWindow}. At the moment, the console.log is not outputting anything when I click inside the div window and then out.

JavaScript

Advertisement

Answer

This is not how you introduce side effects in React, adding an event listener to an element is a side effect, and side effects should be created inside a useEffect.

Here is the problem with your code

JavaScript

The solution is to use useEffect

JavaScript

EDIT What is mentioned above is correct, but you also have another problem, div elements do not receive focus events by default, and so wont blur. If you want an element to blur, and focus, then add tabIndex to it, so on your div do

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement