React.js / React Forms and Validation
Handling Forms and Input in React
This tutorial will guide you through the process of handling forms and user input in a React application. You'll learn how to create forms, capture user input, and manage form sta…
Section overview
5 resourcesExplores handling forms, input, and validation in React applications.
1. Introduction
In this tutorial, we will be learning how to handle forms and user input in a React application. By the end of this tutorial, you will have a clear understanding of how to create forms, capture user input, and manage form state in React.
You will learn:
- Basics of handling forms in React
- How to capture user input in forms
- How to manage form state in React
Prerequisites:
- Basic understanding of JavaScript
- Familiarity with React and its syntax
2. Step-by-Step Guide
In React, form data is usually handled by the components. When the state changes, the component re-renders.
Controlled Components in React:
In HTML, form elements like <input>, <textarea>, and <select> typically maintain their own state and update it based on user input. In React, mutable state is typically kept in the state property of components, and only updated with setState().
3. Code Examples
Here is a simple example of a form with a single input.
class NameForm extends React.Component {
constructor(props) {
super(props);
this.state = {value: ''};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({value: event.target.value});
}
handleSubmit(event) {
alert('A name was submitted: ' + this.state.value);
event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Name:
<input type="text" value={this.state.value} onChange={this.handleChange} />
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
ReactDOM.render(
<NameForm />,
document.getElementById('root')
);
In this code, the NameForm component has a state with a value property. This value is updated every time the user types in the input field thanks to the handleChange method. When the form is submitted, the handleSubmit method is triggered, showing an alert with the inputted name.
4. Summary
In this tutorial, we've learned how to create a form in React, capture user input, and manage the form's state. We've seen that in React, the form's state is typically kept in the component's state property and only updated with setState().
5. Practice Exercises
Exercise 1: Create a form with two input fields: "First Name" and "Last Name". Show an alert with the inputted names when the form is submitted.
Solution:
class NameForm extends React.Component {
constructor(props) {
super(props);
this.state = {
firstName: '',
lastName: ''
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({
[event.target.name]: event.target.value
});
}
handleSubmit(event) {
alert('Name was submitted: ' + this.state.firstName + ' ' + this.state.lastName);
event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
First Name:
<input type="text" name="firstName" value={this.state.firstName} onChange={this.handleChange} />
</label>
<label>
Last Name:
<input type="text" name="lastName" value={this.state.lastName} onChange={this.handleChange} />
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
ReactDOM.render(
<NameForm />,
document.getElementById('root')
);
In this code, we have two input fields, each with its own value in the state. The handleChange method is updated to handle the change of any input field, thanks to the dynamic key [event.target.name].
Exercise 2: Expand the previous form by adding a "Favorite Color" dropdown field with options "Red", "Green", "Blue". Show an alert with the inputted names and selected color when the form is submitted.
Solution:
class NameForm extends React.Component {
constructor(props) {
super(props);
this.state = {
firstName: '',
lastName: '',
favoriteColor: ''
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({
[event.target.name]: event.target.value
});
}
handleSubmit(event) {
alert('Name was submitted: ' + this.state.firstName + ' ' + this.state.lastName + ', Favorite color: ' + this.state.favoriteColor);
event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
First Name:
<input type="text" name="firstName" value={this.state.firstName} onChange={this.handleChange} />
</label>
<label>
Last Name:
<input type="text" name="lastName" value={this.state.lastName} onChange={this.handleChange} />
</label>
<label>
Favorite Color:
<select name="favoriteColor" value={this.state.favoriteColor} onChange={this.handleChange}>
<option value="red">Red</option>
<option value="green">Green</option>
<option value="blue">Blue</option>
</select>
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
ReactDOM.render(
<NameForm />,
document.getElementById('root')
);
In this code, we added a dropdown field for "Favorite Color". The handleChange method works for this field as well, showing the flexibility of this approach.
Tips for further practice: Try adding more fields to the form, such as a checkbox or a radio button group. Experiment with different form validation rules and feedback messages for the user.
Need Help Implementing This?
We build custom systems, plugins, and scalable infrastructure.
Related topics
Keep learning with adjacent tracks.
Popular tools
Helpful utilities for quick tasks.
Random Password Generator
Create secure, complex passwords with custom length and character options.
Use toolLatest articles
Fresh insights from the CodiWiki team.
AI in Drug Discovery: Accelerating Medical Breakthroughs
In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…
Read articleAI in Retail: Personalized Shopping and Inventory Management
In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …
Read articleAI in Public Safety: Predictive Policing and Crime Prevention
In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…
Read articleAI in Mental Health: Assisting with Therapy and Diagnostics
In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…
Read articleAI in Legal Compliance: Ensuring Regulatory Adherence
In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…
Read article