I need to activate a function when the Delete or Backspace keys are pressed. The call is made inside a number input filed which is part of a form. This works:
onKeyUp={((e) => this.onCero(e))}
This does not work:
onKeyDown ={((e) => this.onCero(e))}
The function I am calling:
onCero = (e) => {
e.preventDefault();
if (e.key === "Delete" || e.key === "Backspace") {
alert(e.key);
}
};
I need to trigger the function when the key is pressed, not when it is released using React or JavaScript.
Any ideas guys? Thanks.
I need to activate a function when the Delete or Backspace keys are pressed. The call is made inside a number input filed which is part of a form. This works:
onKeyUp={((e) => this.onCero(e))}
This does not work:
onKeyDown ={((e) => this.onCero(e))}
The function I am calling:
onCero = (e) => {
e.preventDefault();
if (e.key === "Delete" || e.key === "Backspace") {
alert(e.key);
}
};
I need to trigger the function when the key is pressed, not when it is released using React or JavaScript.
Any ideas guys? Thanks.
Share Improve this question edited Sep 18, 2018 at 7:24 Mehravish Temkar 4,3653 gold badges28 silver badges46 bronze badges asked Sep 18, 2018 at 7:23 TowerssTowerss 6742 gold badges13 silver badges31 bronze badges 2-
Sidenote:
onCero
is already bound to the instance and has the signature of an event handler. No need to wrap it in another arrow-function.onKeyDown={this.onCero}
. That way you don't change the props of the input (at least not through this). Therefore less unnecessary updates – Thomas Commented Sep 18, 2018 at 7:48 - @Thomas, thanks mate, you are right. My intention is to run the function inside the onKey event. Just took it outside for testing, that is the reason of the arrow function there :) – Towerss Commented Sep 18, 2018 at 22:43
3 Answers
Reset to default 2You can use the classic JavaScript's event listeners for that.
It would be something like this:
ponentDidMount() {
document.addEventListener('keydown', this.onCero, false);
}
ponentWillUnmount() {
document.removeEventListener('keydown', this.onCero, false);
}
And then use can use the key codes in your onCero function:
onCero = (e) => {
if (e.keyCode === 27 || e.keyCode === 13) {
alert(e.keyCode);
}
};
Your code seems to be working fine.
class App extends React.Component{
constructor(props){
super(props);
}
onCero = (e) => {
console.log(e.key);
e.preventDefault();
if (e.key === "Delete" || e.key === "Backspace") {
alert(e.key);
}
};
render(){
return(
<input type="number" onKeyDown ={((e) => this.onCero(e))} />
)
}
}
ReactDOM.render(
<App/>,
document.getElementById("root")
);
<script src="https://cdnjs.cloudflare./ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare./ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
You can call it via onKeyPress={this.onCero}. This should work