1

I have component where it displays questions . Each question is react component. On press of Enter it should navigate to next question. I have wired onKeyPress to Div element , but event gets captured sometimes , and sometimes it doesn't.

<div className="-" onKeyPress={(e) => this.navigateToNext(e)}>
    <div className="preview-head">
     //Other stuff here
    </div>{/* preview-container*/}
</div>

navigateToNext(e) { 
    if (option.get('selected') === true && e.charCode === 13) {
                this.goToNextQuestion();
    }
}

Can anyone tell me any other way to handle this problem.

2 Answers 2

3

I would wire up an event listener in componentWillMount for the keyup event and check it's the enter key. Just remember to remove the event listener in componentWillUnmount.

I would guess the issue is around the div having focus or not. If it is not focused the key press event doesn't fire on that element and thus nothing happens

Sign up to request clarification or add additional context in comments.

2 Comments

Isn't it bad idea to use keyUp Listener ?
It depends which event you want to listen to. There is nothing wrong with listening for keyup.
0

As said by @spirift, your div has not the focus. Try this :

Add ref={(c) => { this.ref = c }} to your div and focus in a lifecycle method :

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

Comments

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.