21

I am trying to handle an event when the user presses the Backspace button.

I saw this, and I guess I can find Backspace key code using

console.log("Did you delete it? " + e.keyCode);

but the value of e.keyCode is undefined.

Here is the code:

define(["react"], (React) => {
  var TypingContainer = React.createClass({
    keypressed(e) {
      console.log("Did you delete it? " + e.keyCode);
    },

    handleChange: function(e) {
      // if (e.keycode == 8)
        console.log("Did you delete it? " + e.keyCode);
    },

    render: function() {
      return (
         <div>
            <input
              className="typing-container"
              value={this.state.message}
              onChange={this.handleChange}
              onKeyPress={this.keypressed}
            />
         </div>
      );
    }
  })

  return TypingContainer;
});

Update: With the onKeyPress event, I always get 0.

Christopher Bradshaw
  • 2,615
  • 4
  • 24
  • 38
Jeff
  • 7,767
  • 28
  • 85
  • 138
  • 1
    You should probably listen to a different event if you want to get the key code. See https://facebook.github.io/react/docs/events.html#keyboard-events . – Felix Kling Apr 06 '16 at 05:56
  • @FelixKling i have edited my question – Jeff Apr 06 '16 at 06:25
  • [`keyCode`](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode) is deprecated. You should probably be using [`key`](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key) instead. With that, `e.keycode == 8` would become `e.key === 'Backspace'`. – Christopher Bradshaw May 20 '20 at 21:43

3 Answers3

39

You have to listen to the onKeyDown event to capture the delete action. Example:

var InputDemo = React.createClass({
    getInitialState: function() {
        return {
            message: ''
        };
    },

    onKeyDown: function(e) {
        if (e.keyCode === 8) {
            console.log('delete');
        }
    },

    handleChange: function(e) {
        this.setState({
            message: e.target.value
        });
    },

    render: function() {
        return (
            <div>
                <input
                    value={this.state.message}
                    onChange={this.handleChange}
                    onKeyDown={this.onKeyDown}
                />
            </div>
        );
    }
});

Running fiddle: https://jsfiddle.net/7eu41pzz/1/

Christopher Bradshaw
  • 2,615
  • 4
  • 24
  • 38
Richard Rutsche
  • 1,156
  • 8
  • 11
2

Depending on your implementation you should use onKeyUp which should ensure the value of the input has been modified before the event is fired.

Based on the above answer

var InputDemo = React.createClass({

    getInitialState: function() {
    return {
        message: ''
    };
  },
  onKeyUp: function(e) {
    // This would have the current value after hitting backspace.
    if (e.keyCode === 8) { 
     console.log('delete');
     console.log(`Value after clearing input: "${e.target.value}"`)
     // Value after clearing input: ""
    }
  },
  onKeyDown: function(e) {
    // This would have the value set regardless of hitting backspace "test"
    if (e.keyCode === 8) { 
     console.log('delete');
     console.log(`Value after clearing input: "${e.target.value}"`)
     // Value after clearing input: "Test"
    }
  },
  handleChange: function(e) {
    this.setState({
        message: e.target.value
    });
  },
  render: function() {
    return (
       <div>
          <input
            value={this.state.message}
            onChange={this.handleChange}
            onKeyDown={this.onKeyDown}
            onKeyUp={this.onKeyUp}
          />
       </div>
    );
  }
});

These events that are triggered when a key is pressed are in the following order:

keydown Event: This event occurs when the user has pressed down the key. It will occur even if the key pressed does not produce a character value.

keypress Event: This event occurs when the user presses a key that produces a character value. These include keys such as the alphabetic, numeric, and punctuation keys. Modifier keys such as ‘Shift’, ‘CapsLock’, ‘Ctrl’ etc. do not produce a character, therefore they have no ‘keypress’ event attached to them.

keyup Event: This event occurs when the user has released the key. It will occur even if the key released does not produce a character value.

jackotonye
  • 3,537
  • 23
  • 31
2

My approach is far simpler. You would normally have some initial/default state:

import React, { useState } from 'react';

const initialState = {
  firstName: '',
  lastName: '',
  streetAddress1: '',
  streetAddress2: '',
  city: '',
  state: '',
  postCode: '',
  country: '',
  phone: '',
};

const Demo = () => {
  const [state, setState] = useState(initialState);

  const handleChange = (prop) => (e) => {
    setState({
      ...state,
      [prop]: e.target.value || e.target.checked || initialState[prop],
    });
  };

  return (
    <div>
      <label htmlFor="first-name">First Name</label>
      <br />
      <input
        id="first-name"
        value={state.firstName}
        onChange={handleChange('firstName')}
        aria-label="First Name"
      />
      <br />
      <label htmlFor="last-name">Last Name</label>
      <br />
      <input
        id="last-name"
        value={state.lastName}
        onChange={handleChange('lastName')}
        aria-label="Last Name"
      />
      <p>{`${state.firstName} ${state.lastName}`}</p>
    </div>
  );
}

export default Demo;

https://codesandbox.io/s/happy-albattani-kgmq1?file=/src/Demo.js