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.
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>