Introduction to Forms in React
Learn how to create forms in React, collect user input, and handle form data using React components.
1. Introduction to Forms
Forms are used to collect information from users. Examples include login forms, registration forms, contact forms, and feedback forms.
In React, we can create forms using HTML form elements such as input, textarea, select, and button. React helps us manage the input values and respond when a user submits a form.
2. Creating a Basic Form in React
A basic React form can contain labels, input fields, and a submit button. JSX is used to describe the form elements that React displays on the page.
Example
function ContactForm() {
return (
<form>
<label htmlFor="name">Name:</label>
<input
type="text"
id="name"
name="name"
/>
<button type="submit">
Submit
</button>
</form>
);
}
export default ContactForm;
Expected Output
Contact Form
The form displays a text input and a submit button. The example demonstrates the structure of a form; it does not yet process or store the entered value.
3. Common Form Elements
React supports standard HTML form elements. Each element is used to collect a particular type of information.
| Element | Purpose | Example |
|---|---|---|
input |
Accepts user input. | Name or email |
textarea |
Accepts multiline text. | Comments |
select |
Provides a list of options. | Select a course |
button |
Allows users to perform an action. | Submit |
label |
Describes a form field. | Email Address |
4. Understanding Form Structure
A form groups related input fields and provides a way for users to submit the information they enter.
This is the general workflow of a form. The exact processing depends on how the React component is implemented.
5. Understanding Form Input Values
An input element allows a user to enter information. In React, we can use state to store the input value and update it whenever the user types.
Example: Managing a Name Field
import { useState } from "react";
function NameForm() {
const [name, setName] = useState("");
function handleChange(event) {
setName(event.target.value);
}
return (
<div>
<label htmlFor="studentName">
Student Name:
</label>
<input
id="studentName"
type="text"
value={name}
onChange={handleChange}
/>
<p>Entered Name: {name}</p>
</div>
);
}
export default NameForm;
Expected Output
Entered Name: Rahul
The useState hook stores the name, and the onChange handler updates the state when the input value changes. React then displays the updated value.
6. Understanding Form Submission
Form submission occurs when a user submits the form, commonly by clicking a submit button. React applications can handle submission with an onSubmit event handler.
Example
function FeedbackForm() {
function handleSubmit(event) {
event.preventDefault();
console.log("Form submitted");
}
return (
<form onSubmit={handleSubmit}>
<label htmlFor="feedback">
Feedback:
</label>
<input
id="feedback"
name="feedback"
type="text"
/>
<button type="submit">
Submit Feedback
</button>
</form>
);
}
export default FeedbackForm;
Expected Result
When the form is submitted in the running React application, the browser's default form submission is prevented and "Form submitted" is written to the console.
event.preventDefault() prevents the browser's
default form submission behavior. It does not automatically
save the form data.
7. React Forms and State
State is useful when a component needs to remember the values entered by a user. A controlled input receives its value from React state and updates that state through an event handler.
Example
import { useState } from "react";
function EmailForm() {
const [email, setEmail] = useState("");
return (
<div>
<label htmlFor="email">Email:</label>
<input
id="email"
type="email"
value={email}
onChange={(event) =>
setEmail(event.target.value)
}
/>
<p>Email: {email}</p>
</div>
);
}
export default EmailForm;
Expected Output
Email: student@example.com
The email state stores the current input value. When the user types, the onChange handler updates the state and React displays the new value.
8. Common Mistakes
Mistake 1: Using an Incorrect Label Association
<label>Email</label>
<input type="email" id="email" />
The label is not explicitly connected to the input. Associating them improves usability and accessibility.
Correct Code
<label htmlFor="email">Email</label>
<input type="email" id="email" />
Mistake 2: Forgetting to Update State
<input
value={name}
onChange={() => {}}
/>
The handler does not update the name state, so the controlled input cannot reflect new values entered by the user.
Correct Code
<input
value={name}
onChange={(event) =>
setName(event.target.value)
}
/>
Mistake 3: Forgetting to Prevent Default Submission
function handleSubmit(event) {
console.log("Form submitted");
}
If you want to handle the form submission in React without the browser's default submission behavior, call preventDefault() in the submit handler.
Correct Code
function handleSubmit(event) {
event.preventDefault();
console.log("Form submitted");
}
9. Practice Tasks
Complete these tasks to practise creating forms in React.
Summary
Forms in React collect information from users through elements such as input, textarea, select, and button. React components can use state to store input values and update them when users type. Event handlers can respond to changes and form submissions, while event.preventDefault() prevents the browser's default submission behavior when needed. These fundamentals provide the foundation for controlled components, input handling, form validation, and form submission.