ApurvG ApurvG - 4 years ago 164
React JSX Question

Login using enter key

I have login form in my app. Currrently I have a Login button to login. When this login button is clicked, I send the username and password values to the backend api which in turn generates a token and allow the user to move to next screen if authenticated. I want the same functionality when I press enter key. I have looked to many sources but I need a secure way. How can I do it. This is my form component

render(){
return (
<div className="LoginPage">
<div className="login-page">
<div className="form">
<form className="login-form">
<input id="username" type="username" placeholder="username"/>
<input id="password" type="password" placeholder="password"/>
<p className="message">Not registered? <a href="#">Request Username and Password</a></p>
</form>
<button onClick={this.handleLoginButtonClick.bind(this)}>login</button>
</div>
</div>
</div>
);
}

Answer Source

Use the onKeyDown event with input fields, and in this method check the keycode of the key pressed by the user, Key code of Enter key is 13, so whenever he pressed enter, call the same method that you are calling on button click, Write it like this:

render(){
    return (
        <div className="LoginPage">
            <div className="login-page">
                <div className="form">
                    <form className="login-form">
                        <input id="username" type="username" placeholder="username" onKeyDown={this.onKeyDown.bind(this)}/>
                        <input id="password" type="password" placeholder="password" onKeyDown={this.onKeyDown.bind(this)}/>
                        <p className="message">Not registered? <a href="#">Request Username and Password</a></p>
                    </form>
                    <button onClick={this.handleLoginButtonClick.bind(this)}>login</button>
                </div>
            </div>
        </div>
    );
}

onKeyDown(e){
   if(e.keyCode == 13){
     /*write the logic here*/
   }
}

You need to use ref to focus the field if user left them blank. Check jsfiddle for working example with focusing the field: https://jsfiddle.net/ygytaj6s/

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download