Last active
August 1, 2023 21:00
-
-
Save pstoica/4323d3e6e37e8a23dd59 to your computer and use it in GitHub Desktop.
onBlur for entire react element
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function OnBlurComponent({ onBlur }) { | |
const handleBlur = (e) => { | |
const currentTarget = e.currentTarget; | |
// Check the newly focused element in the next tick of the event loop | |
setTimeout(() => { | |
// Check if the new activeElement is a child of the original container | |
if (!currentTarget.contains(document.activeElement)) { | |
// You can invoke a callback or add custom logic here | |
onBlur(); | |
} | |
}, 0); | |
}; | |
return ( | |
<div tabIndex="1" onBlur={handleBlur}> | |
Hello <input type="text" value="world" /> | |
</div> | |
); | |
} |
That helps a lot!
You can also use event.relatedTarget
to get the next active element on blur if you don't care about IE 11.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You're my hero!