How to prevent propagation in nested components
See original GitHub issueI have the following use case: a select dropdown, inside a modal.
I want to be able to set things up so that if the ‘escape’ key is hit when the dropdown is not open, it closes the modal, but if the dropdown IS open, it only closes the dropdown (and not the modal).
I’m testing this idea using the following, basic approach:
const Dropdown = () => {
useHotkeys("esc", () => (e) => {
e.preventDefault();
e.stopPropagation();
console.log("Dropdown escape");
}, {
enableOnTags: ["INPUT"],
});
return (<div>Dropdown</div>)
}
const Modal = () => {
useHotkeys("esc", () => console.log("Modal escape"), {
enableOnTags: ["INPUT"],
});
return (<Dropdown />)
}
I would have thought that using preventDefault and / or stopPropagation would do the trick here, but when I try running this code, the console.log fires twice, one for each component.
I’m probably not going about this the right away, so any help would be greatly appreciated.
Issue Analytics
- State:
- Created a year ago
- Comments:6 (2 by maintainers)
Top Results From Across the Web
Event bubbling due to nested components - how to stop ...
I am working on a project in which I am facing a problem with event bubbling. I have 2 nested components, each containing...
Read more >How can I prevent event bubbling in nested React ...
I've played around with e.preventDefault(), e.stopPropagation(), to no avail. class List extends React.Component { ...
Read more >Event Bubbling and Event Catching in JavaScript and React
event.stopPropagation() ... This will stop any parent component's event from firing. To use this: ... Note that I changed the parent's div back...
Read more >Material-ui: How to stop propagation of click event in nested ...
The workaround I suggest is the following: render() { return ( <Paper onClick={this._onClick}> <IconMenu iconButtonElement={iconButtonElement}> {menuItems} ...
Read more >Configure Event Propagation - Salesforce Developers
Event retargeting preserves component encapsulation and prevents exposing a component's internals. For example, a click listener on <my-button> always receives ...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
useHotkeys
accepts a generic to type the ref:const ref = useHotkeys<HTMLDivElemen>(...)
I completely missed this 🤦 Thank you so much for the quick response and help!