2

So basically I have a login page without a form and I want to trigger the login button's onClick when the user presses enter.

I tried adding an event listener to the page like so:

componentWillMount() { const { handleKeyPress, username, password } = this.props; document.addEventListener('keydown', (event, username, password) => handleKeyPress(event.key)); } 

The problem is that that listener is instantiated when the component mounts which means that the props username and password are in their initial state (i.e. empty).

Adding the event listener to componentWillReceiveProps doesn't work for similar reasons.

Basically with this solution I'd need to not send username and password from the function in the event listener and instead fetch username and password from the state in mapDispatchToProps where the function in the event listener is defined, but that's a very ugly solition.

What I was looking for in the beginning was to add a listener to the button similar to onClick and basically as such:

<button onEnterKeyPress={() => handleLogin(this.props.username, this.propspassword)} > Log in </button> 

But as far as I know there is no way of doing that... hopefully I'm wrong though! If anyone has some ideas, please share.

2 Answers 2

0
constructor() { super(); this.handleKeyPress = this.handleKeyPress.bind(this); } componentWillMount() { document.addEventListener('keydown', this.handleKeyPress); } handleKeyPress(event) { if (event.keyCode !== 13) return; const {handleLogin, username, password} = this.props; handleLogin(username, password); } componentWillUnmount() { document.removeEventListener('keydown', this.handleKeyPress); } 
Sign up to request clarification or add additional context in comments.

2 Comments

Above answer plus binding this to the function as such works: this.handleKeyPress = this.handleKeyPress.bind(this); Not as nice as creating the function inline in MDTP but a decent solution. Thanks! Accepting your answer, please edit your answer and add the binding. You also need to add the second argument to removeEventListener btw.
Added bind, although if you use the createClass there is no need for it :) Happy to help!
-1

onKeyPress={event => {if (event.key === "Enter") {function_name}}}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.