Skip to content

Instantly share code, notes, and snippets.

@pstoica
Last active September 9, 2024 05:14
Show Gist options
  • Save pstoica/4323d3e6e37e8a23dd59 to your computer and use it in GitHub Desktop.
Save pstoica/4323d3e6e37e8a23dd59 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>
);
}
@StanielPetrov
Copy link

OMG, you are a genius! Thank you so much for sharing this!

@HermanNygaard
Copy link

@pstoica
Thanks for this! Just a heads up, I think you forgot to change the callback onBlur={onBlur} to onBlur={handleBlur} in the newest revision:

return (
    <div tabIndex="1" onBlur={handleBlur}>
      Hello <input type="text" value="world" />
    </div>
  );

@pstoica
Copy link
Author

pstoica commented Mar 12, 2021

@pstoica
Thanks for this! Just a heads up, I think you forgot to change the callback onBlur={onBlur} to onBlur={handleBlur} in the newest revision:

return (
    <div tabIndex="1" onBlur={handleBlur}>
      Hello <input type="text" value="world" />
    </div>
  );

glad it helped. thanks for catching that, updated!

@AshlandWest
Copy link

You're my hero!

@gattonero1052
Copy link

That helps a lot!

@diegohaz
Copy link

You can also use event.relatedTarget to get the next active element on blur if you don't care about IE 11.

@YogeshR6
Copy link

YogeshR6 commented Sep 9, 2024

@diegohaz I was look for this for so long, thanks a lot. Was working with emoji pickers and for some reason document.activeElement does not work when I click on the picker itself and closes the pop over even though it is a part of the div, but using event.relatedTarget works perfectly fine now.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment