I want to bind to close the active react bootstrap popover on escape
press .Here is the code
_handleEscKey:function(event){ console.log(event); if(event.keyCode == 27){ this.state.activePopover.hide(); } }, componentWillMount:function(){ BannerDataStore.addChangeListener(this._onchange); document.addEventListener("click", this._handleDocumentClick, false); document.addEventListener("keyPress", this._handleEscKey, false); }, componentWillUnmount: function() { BannerDataStore.removeChangeListener(this._onchange); document.removeEventListener("click", this._handleDocumentClick, false); document.removeEventListener("keyPress", this._handleEscKey, false); },
But nothing is getting logged in the console when I press any key. I have tried to listen that on window also and with different cases .'keypress','keyup' etc but it seem I am doing something wrong .
To detect when the user pressed the Enter key when typing in an input field: Add the onKeyDown prop to the input element. Every time the user presses a key in the input field, check if the pressed key is Enter.
To use the addEventListener method in function components in React: Set the ref prop on the element. Use the current property on the ref to get access to the element. Add the event listener in the useEffect hook.
You should use keydown
and not keypress
.
Keypress (deprecated) is usually used only for keys that produce a character output as per the docs
Keypress (deprecated)
The keypress event is fired when a key is pressed down and that key normally produces a character value
Keydown
The keydown event is fired when a key is pressed down.
Just had a similar problem with this myself. I'll use your code to illustrate a fix.
// for other devs who might not know keyCodes var ESCAPE_KEY = 27; _handleKeyDown = (event) => { switch( event.keyCode ) { case ESCAPE_KEY: this.state.activePopover.hide(); break; default: break; } }, // componentWillMount deprecated in React 16.3 componentDidMount(){ BannerDataStore.addChangeListener(this._onchange); document.addEventListener("click", this._handleDocumentClick, false); document.addEventListener("keydown", this._handleKeyDown); }, componentWillUnmount() { BannerDataStore.removeChangeListener(this._onchange); document.removeEventListener("click", this._handleDocumentClick, false); document.removeEventListener("keydown", this._handleKeyDown); },
Since you are using the createClass way of doing things, you do not need to bind to certain methods as this
is implicit in each method defined.
There is a working jsfiddle, using the createClass method of React component creation here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With