Skip to content

Instantly share code, notes, and snippets.

@jbournonville
Forked from pstoica/OnBlurComponent.jsx
Created February 2, 2021 14:40
Show Gist options
  • Save jbournonville/2c6badaa9963b49a05c464fb4c1c1c03 to your computer and use it in GitHub Desktop.
Save jbournonville/2c6badaa9963b49a05c464fb4c1c1c03 to your computer and use it in GitHub Desktop.
onBlur for entire react element
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>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment