Tuesday, 22 January 2019

How to set focus of an input field using React JS?

To set focus on an input field by using Ref.

import React, { Component } from 'react';

class LoginForm extends Component {
username = React.createRef();
state = {}
handleSubmit = e => {
// Call the server
e.preventDefault();
const username = this.username.current.value;
alert(username);
};

componentDidMount()
{
this.username.current.focus();
}
render() {
return (
<div>
<div class="form-row">
<form onSubmit={this.handleSubmit}>
<div className="form-group col-md-12">
<label htmlFor="username">Email address</label>
<input ref={this.username} type="email" className="form-control" id="username" aria-describedby="emailHelp" placeholder="Enter email" />
<small id="emailHelp" className="form-text text-muted">We'll never share your email with anyone else.</small>
</div>
<div className="form-group col-md-12">
<label htmlForfor="InputPassword1">Password</label>
<input type="password" className="form-control" id="InputPassword1" placeholder="Password" />
</div>
<div className="form-check">
<input type="checkbox" className="form-check-input" id="Check1" />
<label className="form-check-label" for="Check1">Check me out</label>
</div>
<button type="submit" className="btn btn-primary m-2">Submit</button>
</form>
</div>
</div>
);
}
}

export default LoginForm;

Now the cursor will blink when page loads initially. See the below screen.































Without using Ref also we can achieve this. See the below-highlighted code.


import React, { Component } from 'react';

class LoginForm extends Component {
username = React.createRef();
state = {}
handleSubmit = e => {
// Call the server
e.preventDefault();
const username = this.username.current.value;
alert(username);
};

// componentDidMount()
// {
// this.username.current.focus();
// }
render() {
return (
<div>
<div class="form-row">
<form onSubmit={this.handleSubmit}>
<div className="form-group col-md-12">
<label htmlFor="username">Email address</label>
<input autoFocus
ref={this.username} type="email" className="form-control" id="username" aria-describedby="emailHelp" placeholder="Enter email" />
<small id="emailHelp" className="form-text text-muted">We'll never share your email with anyone else.</small>
</div>
<div className="form-group col-md-12">
<label htmlForfor="InputPassword1">Password</label>
<input type="password" className="form-control" id="InputPassword1" placeholder="Password" />
</div>
<div className="form-check">
<input type="checkbox" className="form-check-input" id="Check1" />
<label className="form-check-label" for="Check1">Check me out</label>
</div>
<button type="submit" className="btn btn-primary m-2">Submit</button>
</form>
</div>
</div>
);
}
}

export default LoginForm;



No comments:

Post a Comment