I know that withkeypress or keyDown I can check which key is pressed, but with onClick I'm not able to do so.

class App extends React.Component {
  handleClick = e => {
    console.log(e.keyCode);
  };
  render() {
    return <h1 onClick={this.handleClick}>Hello CodeSandbox</h1>;
  }
}

https://codesandbox.io/s/ovwn9z6owz

What's the issue here?

3 Answers

4
Sagiv b.g On

keycode is for KeyboardEvent not mouse clicks and anyway considered obsolete.
From the Keyboard​Event​.key​Code MDN:

This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

3
AdityaParab On

The onClick prop of react dispatches React.ClickEvent which doesn't have a keyCode property. Since it's a mouse event, the existence of keyboard related properties on the event object is illogical.

The keyboard related properties exist on React.KeyboardEvent which is dispatched by react's keyboard event related props such as onChange, onKeyup, onKeyDown etc

https://codesandbox.io/s/kkv9ol6pr7

0
Divakar Vishwamithra On

Hi here you're using h1 tag, in this tag not possible to handle onClick function do it in Button tag and then try it works.

and you need to send a parameter inside the onClick like onClick={(e) => this.handleClick(e)}

<Button onClick={(e) => this.handleClick(e)}>Hello CodeSandbox</Button>

for particular keyCode you go throug the below link

Key Code