Ben Shekhtman
Ben Shekhtman

Reputation: 615

React cannot detect 'delete key' in my KeyDown event

I have been trying for days to capture a 'delete' key press in React. My function is always evaluating to false. why?

          <textarea
            className="DetailsPage-txt-area"
            placeholder="Write a short bio about yourself..."
            value={bio}
            onChange={handleSetBio}
            onKeyDown={(e) => handleKeyDown(e)}
          ></textarea>
  const handleKeyDown = (e) => {
    if (e.keyCode === 46) {
      console.log('true');
    } else {
      console.log('false')
    }
  }

Upvotes: 0

Views: 1606

Answers (1)

Viet
Viet

Reputation: 12779

46 is keyCode of Delete. But I think you press backspace with keyCode is 8. So just update to handle 2 case.

if (e.keyCode === 46 || e.keyCode === 8) {
  console.log('true');
} else {
  console.log('false')
}

Upvotes: 1

Related Questions