Search code examples
reactjskeypressmouseclick-event

Handling onClick and onKeyPressDown in the same function React


In React, I have a div that when clicked with a mouse, or tabbed and pressed enter or space upon, activates (it uses both onClick and onKeyPressDown to trigger the same function). However, I'm not sure how I can only account for mouse click events or enter/space events. For example, I don't want the function's setState call running if someone just hits a random key.

toggleFunction = () => {
     if (event.key === " " || event.key === "Enter") {
        this.setState({ this.state.pressed: !this.state.pressed })
     } 
}

<div onClick={this.toggleFunction} onKeyPressDown={this.toggleFunction}

In toggleFunction, how can I ensure that if a mouseclick occurs the state will change, but if a button that's not enter or space is pressed it does not change?


Solution

  • You can use event.type to distinguish between different events like mouse/keyboard clicks

    toggleFunction = (event) => {
         if (event.type === 'mousedown' || (event.type === 'keydown' && (event.key === " " || event.key === "Enter"))) {
            this.setState({ this.state.pressed: !this.state.pressed })
         } 
    }