Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJS OnKeyPress to trigger a button press

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?

like image 693
chakolatemilk Avatar asked Aug 29 '17 23:08

chakolatemilk


People also ask

How do you trigger keypress event in react JS?

How do you trigger keypress event in React JS? If you're trying to create a keyboard event, you can make use of KeyboradEvent constructor. An enter key event can be dispatched like: const event = new KeyboardEvent('keypress', { key: 'enter', }); console.

How do I automatically trigger a button click after 5 seconds with React?

You could create a ref for the <button> and set a timeout inside of an effect hook to call the button click event after 5 seconds. You could throw in a state hook to limit the prompt. Used setInterval instead of setTimeout to retry every 5 seconds.

How do you manually trigger click event in Reactjs?

To add the click event in React using plain JavaScript, you need to use addEventListener() to assign the click event to an element. Create one <button> element as ref props so that it can be accessed to trigger the click event.


2 Answers

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>
    );
  }
}
like image 194
elas Avatar answered Oct 02 '22 12:10

elas


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>
    )
  }
like image 21
Soorena Avatar answered Oct 02 '22 12:10

Soorena