[React] Auto Focus after render

I was building a dynamic form in a React component and encountered a problem. I couldn’t get the form to auto-focus on an input after submission.

I looked into ComponentDidUpdate() and/or ComponentDidMount(), but in the end, there was a simple solution to this.

class SomeForm extends Component {
	handleSubmit = (e) => {
		this.props.onSubmit(this.input.value);
		this.input.value = "";
		e.preventDefault();
	}

	render() {
		return (
			<form onSubmit={this.handleSubmit}>
				<input autoFocus type="text" ref={(input) => this.input = input} />
				<input type="submit" value="Submit" />
			</form>
		);
	}
}

Shown in the code above, by putting autoFocus attribute to true in the input tag, the problem was solved. When the form is rendered, it should automatically focus to the input.

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s