ReactJS OnKeyPress to trigger a button press

chakolatemilk picture chakolatemilk · Aug 30, 2017 · Viewed 19.7k times · Source

I'm very new to ReactJS and I'm just trying to do some small things to understand more.

I was wondering if the OnKeyPress can trigger a button press. I've seen a few similar questions but what the OnKeyPress triggered was just a console.log or an alert. So I wasn't sure how to trigger the button press.

This is what I have so far:

class Form extends React.Component {
  onButtonPress = (e) => {
    // this is just an example of what happens when the button is pressed.
    this.setState({isClicked: true});
  }

  keyPress = (event) => {
    if (event.key == 'Enter'){
      // How would I trigger the button that is in the render? I have this so far.
      this.onButtonPress();
    }
  }

  render() {
    return (
      <div>
        <div className="fieldForm">
          <input
            value={name}
            type="name"
            onKeyPress={this.keyPress}
          />
        </div>
        <Button onClick={this.onButtonPress}>Submit</Button>
      </div>
    )
  }
}

Please note that I didn't include everything in here such as the constructor, props, or the state object attributes.

The purpose of this is to make it look like the button has been clicked. When the button is clicked, it'll show a small loading sign on the button. I want the same thing to happen if I were to press enter (with the loading sign on the button, that's why I want the button pressed).

Is this possible?

Answer

elas picture elas · Aug 30, 2017

Programmatically triggering DOM events is not something you should do unless you have very specific needs.

Both onKeyPress and onClick are event handlers, you can do anything you want when an event happens. I would just call a function that sets the state you want from both handlers.

Here's an example:

class Form extends React.Component {
  handleFormSubmit = () => {
    this.setState({ isClicked: true });
  };

  handleButtonPress = () => {
    this.handleFormSubmit();
  };

  handleKeyPress = event => {
    if (event.key == 'Enter') {
      this.handleFormSubmit();
    }
  };

  render() {
    return (
      <div>
        <div className="fieldForm">
          <input value={name} type="name" onKeyPress={this.handleKeyPress} />
        </div>
        <Button onClick={this.handleButtonPress} loading={this.state.Load}>
          Submit
        </Button>
      </div>
    );
  }
}