ReactJS OnKeyPress to trigger a button press ReactJS OnKeyPress to trigger a button press reactjs reactjs

ReactJS OnKeyPress to trigger a button press


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>    );  }}


In case you have no other way and you should click on this element for some vague reason and the method that elas said didn't work for you. try this:

  onButtonPress = (e) => {    console.log('hi hi')  }  handleKeyPress = (event) => {    if (event.key === 'Enter') {      this.refs.but.click()    }  }  render () {    return (      <Layout>        <div>          <div className="fieldForm">            <input              value={'name'}              type="name"              onKeyPress={(e) => this.handleKeyPress(e)}            />          </div>          <Button onClick={this.onButtonPress} ref="but">Submit</Button>        </div>      </Layout>    )  }