I'm trying to handle key event when load page ponent. First, I have a router:
<Router>
<Route exact path="/" ponent={Home} />
</Router>
In home ponent, 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 ponent in Route. Because, input element can be out-focus and this key event cannot be excute.
Thanks.
I'm trying to handle key event when load page ponent. First, I have a router:
<Router>
<Route exact path="/" ponent={Home} />
</Router>
In home ponent, 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 ponent in Route. Because, input element can be out-focus and this key event cannot be excute.
Thanks.
Share Improve this question asked Nov 7, 2017 at 10:22 Pham Minh TanPham Minh Tan 2,0967 gold badges27 silver badges39 bronze badges2 Answers
Reset to default 6The 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>
Approach 1:
For the event to trigger, your div needs to be selected. To do this you need to focus it in the ponentDidMount 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
ponentDidMount() {
this.div.focus();
}
Approach 2:
Listen to events on the entire document
ponentDidMount() {
document.addEventListener('keydown', this.onKeyDown);
}
ponentWillUnmount() {
document.removeEventListener('keydown', this.onKeyDown);
}