If you mix JS event listeners and React event listeners, you need
event.nativeEvent.stopImmediatePropagation()
We have a Modal including an input.
We would like to close our modal on pressing ESC.
We want to keep the expected bahavior for our input: when focused, be able to blur it on pressing ESC.
We need to stop the event propagation to blur the input without closing the modal.
class Modal extends Component {
componentDidMount() {
document.addEventListener('keydown', this.closeModal);
}
componentWillUnmount() {
document.removeEventListener('keydown', this.closeModal);
}
closeModal = () => console.log('closeModal');
handleKeyDown = (e) => e.stopPropagation();
render() {
return (
<div className="modal">
<input type="text" onKeyDown={this.handleKeyDown} />
</div>
);
}
}
/**
* Action: click the input then press ESC
*
* Output: "closeModal"
*
* => NOK
*/
class Modal extends Component {
componentDidMount() {
document.addEventListener('keydown', this.closeModal);
}
componentWillUnmount() {
document.removeEventListener('keydown', this.closeModal);
}
closeModal = () => console.log('closeModal');
handleKeyDown = (e) => e.nativeEvent.stopImmediatePropagation();
render() {
return (
<div className="modal">
<input type="text" onKeyDown={this.handleKeyDown} />
</div>
);
}
}
/**
* Action: click the input then press ESC
*
* Output:
*
* => OK
*/