0

In my component, i want to fire a fake onKeypress on a specific keycode, is it possible? i have this code:

class componentName extends Component {
 fireKey = e => {
    function makeKeyPressEvent(keyName, keyCode, charCode){
      var event = new KeyboardEvent('keypress');
      Object.defineProperties(event, {
          charCode: {value: charCode},
          keyCode: {value: keyCode},
          keyIdentifier: {value: keyName},
          which: {value: keyCode}
      });
      return event;
    }
    window.addEventListener('keypress', function(event){
      console.log('key pressed!',
        event.keyIdentifier, event.keyCode, event.charCode, event)
    }, true);
    var enterKeyEvent = makeKeyPressEvent('onClick', 39, 39);
    window.dispatchEvent(enterKeyEvent);
  }
  render (

        ) {
    return (
      <div>
        <button onClick={this.fireKey}> > </button>
      </div>
    )
  }
}

or how can i manually change an event keyCode on onClick of button in react?

4
  • what is the reason you would like to simulate key event? Commented Mar 16, 2018 at 17:25
  • i'm using it for a package feature, changes page on right arrow, wanted it on button also Commented Mar 16, 2018 at 17:34
  • well, i don't have any solution for simulating key event (sorry), but i might suggest to you a way to avoid it (well, and most probably it would make your code a little bit cleaner), the action that do all the logic, put inside a function, outside the key event, then inside your key event call that function that do the logic, and the onClick of the button? just the same, so you don't repeat yourself about the logic and didn't have to simulate key event. is it helping? Commented Mar 16, 2018 at 17:44
  • I'm failing to see the need for a keypress event to change a page. Could you explain your use case a little more thoroughly? Commented Mar 16, 2018 at 18:07

1 Answer 1

1
you can use this:-
    class componentName extends Component {
     fireKey = e => {
        if(e.keyCode == 13){        //compare with your keyboard key
                //your code here
             }
      }
      render () {
        return (
          <div>
            <button onKeyPress={this.fireKey}> > </button>
          </div>
        )
      }
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.