Detect when Delete or Backspace keys are pressed with onKeyPress and not with onKeyUp in React.js

Viewed 8373

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.

3 Answers

You can use the classic JavaScript's event listeners for that.

It would be something like this:

componentDidMount() {
  document.addEventListener('keydown', this.onCero, false);
}

componentWillUnmount() {
  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.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/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

Related