3

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 2

6

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>
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks @Daniel Andrei, the simple solution :). It's worked.
You'll likely want to set to -1 since you're manipulating it programmatically. webaim.org/techniques/keyboard/tabindex
6

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);
}

1 Comment

for me this.ref.current.focus()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.