How to handle onKeyDown event on div in ReactJS

Viewed 13582

I'm trying to handle key event when load page component. First, I have a router:

<Router>
    <Route exact path="/" component={Home} />
</Router>

In home component, I try to bind onKeyPress in div element but it's not work. I bind it on input element, it's worked.

return (
        <div onKeyDown={this.__handleKeyDown} className="container" style={{ backgroundImage: `url(${this.state.backgroundbanner})` }}>
            <input
                className="hidden"
                onKeyDown={this.__handleKeyDown}
                ref={(input) => { this.dummyInput = input; }}
                />
            <div className="container-shadow">
                <h1 className="main-title">{this.state.title}</h1>
                <h3 className="main-description">{this.state.description}</h3>
                <ListMovie cursor={ cursor } />
            </div>
        </div>
    )

How to bind event onKeyDown on div element or how to bind key event when load a page component in Route. Because, input element can be out-focus and this key event cannot be excute.

Thanks.

2 Answers

Approach 1:

For the event to trigger, your div needs to be selected. To do this you need to focus it in the componentDidMount event. And to do this you need a ref to your div.

Step 1: get a ref to your div

<div onKeyDown={this.__handleKeyDown} ref={(c) => {this.div = c;}}>

Step 2: Focus it on load

componentDidMount() {
  this.div.focus();
}

Approach 2:

Listen to events on the entire document

componentDidMount() {
    document.addEventListener('keydown', this.onKeyDown);
}

componentWillUnmount() {
    document.removeEventListener('keydown', this.onKeyDown);
}

The reason as to why it doesn't work is that the div element requires the tabIndex attribute in order to be focusable and to handle keyDown events.

<div tabIndex="1" onKeyDown={this.__handleKeyDown}></div>
Related