Creating Forms in React JS
Creating Forms in React JS is an essential concept used to collect, manage, validate, and submit information from users. Forms are commonly used for login pages, registration pages, contact forms, feedback forms, search boxes, checkout pages, and other interactive applications. React provides form elements such as input, textarea, select, checkboxes, and radio buttons. Developers can manage these elements using state, event handlers, validation logic, and form submission functions.
Learn more: JustAcademy React JS Training | Register for React JS Course Demo
1. What Is a Form in React JS?
A form is a user interface component that allows users to enter information and submit it for processing. In React, forms use standard HTML form elements, while React state and event handlers can control how the entered information is managed.
For example, a registration form may collect a user's name, email address, password, and phone number. React can store these values, validate them, and process the information when the user submits the form.
Common Uses of Forms
- Login and registration forms.
- Contact and feedback forms.
- Search forms and filter controls.
- Online application forms.
- Shopping cart and checkout forms.
- Profile editing forms.
- Surveys and questionnaires.
2. Creating a Basic Form in React
A basic React form can be created using the HTML form, label, input, and button elements.
function BasicForm() {
return (
<form>
<label htmlFor="username">Username:</label>
<input
type="text"
id="username"
name="username"
placeholder="Enter your username"
/>
<button type="submit">Submit</button>
</form>
);
}
export default BasicForm;
Explanation:
form groups the form controls.
label describes the input field.
htmlFor connects the label to the input's id in React JSX.
name identifies the field when reading submitted form data.
button type="submit" submits the form.
This example demonstrates the form structure. By default, browser form submission may navigate or reload the page. In many React applications, an onSubmit handler is used to process the data without a full-page reload.
3. Understanding Controlled Components
A controlled component is a form element whose current value is managed by React state. The component receives its value from state, and an onChange handler updates that state when the user types or makes a selection.
import { useState } from "react";
function NameForm() {
const [name, setName] = useState("");
return (
<div>
<label htmlFor="name">Name:</label>
<input
id="name"
type="text"
value={name}
onChange={(event) => setName(event.target.value)}
/>
<p>Your name is: {name}</p>
</div>
);
}
export default NameForm;
How it works:
useState("") initializes the name as an empty string.
- The
value property displays the current state value in the input.
- The
onChange event runs when the user changes the input.
setName() updates the state with the new value.
- React re-renders the component with the updated name.
For a controlled text input, initialize the value with a string, such as "", rather than undefined or null.
4. Understanding Uncontrolled Components
An uncontrolled component keeps its current form value in the DOM rather than using React state to control every change. You can read the form values when the form is submitted by using the browser's FormData API or a React ref.
function UncontrolledForm() {
function handleSubmit(event) {
event.preventDefault();
const formData = new FormData(event.currentTarget);
const username = formData.get("username");
console.log("Username:", username);
}
return (
<form onSubmit={handleSubmit}>
<label htmlFor="username">Username:</label>
<input
id="username"
name="username"
defaultValue=""
/>
<button type="submit">Submit</button>
</form>
);
}
export default UncontrolledForm;
Explanation: The input is not controlled by a React state variable. When the user submits the form, FormData reads the value associated with the input's name.
Controlled vs. Uncontrolled Components
| Feature |
Controlled |
Uncontrolled |
| Current value |
Managed by React state |
Managed by the DOM |
| Value access |
Read from state |
Read through FormData or a ref |
| Change handling |
Usually uses onChange and a state setter |
Does not require state for each field |
| Validation while typing |
Easy to implement with state |
Can be implemented with DOM APIs and events |
| Suitable for |
Interactive forms and dynamic validation |
Simple forms where values are needed mainly at submission |
5. Handling Form Submission
The onSubmit event lets you run a function when the user submits a form. Calling event.preventDefault() prevents the browser's default submission behavior so the React application can handle the submission.
import { useState } from "react";
function LoginForm() {
const [username, setUsername] = useState("");
const [email, setEmail] = useState("");
function handleSubmit(event) {
event.preventDefault();
console.log("Username:", username);
console.log("Email:", email);
}
return (
<form onSubmit={handleSubmit}>
<label htmlFor="username">Username:</label>
<input
id="username"
value={username}
onChange={(event) => setUsername(event.target.value)}
required
/>
<label htmlFor="email">Email:</label>
<input
id="email"
type="email"
value={email}
onChange={(event) => setEmail(event.target.value)}
required
/>
<button type="submit">Login</button>
</form>
);
}
export default LoginForm;
Explanation: The form uses controlled inputs. When submitted, the handler prevents a page reload and reads the values from React state. In a real login application, the form data should be sent to a secure backend rather than merely logged to the console.
6. Using Multiple Input Fields
A form often contains multiple fields. You can create a separate state variable for each field or manage related values in a single state object.
Example: Managing Multiple Fields with One State Object
import { useState } from "react";
function RegistrationForm() {
const [formData, setFormData] = useState({
name: "",
email: "",
phone: ""
});
function handleChange(event) {
const { name, value } = event.target;
setFormData((previousData) => ({
...previousData,
[name]: value
}));
}
function handleSubmit(event) {
event.preventDefault();
console.log("Form Data:", formData);
}
return (
<form onSubmit={handleSubmit}>
<label htmlFor="name">Full Name:</label>
<input
id="name"
name="name"
value={formData.name}
onChange={handleChange}
required
/>
<label htmlFor="email">Email:</label>
<input
id="email"
name="email"
type="email"
value={formData.email}
onChange={handleChange}
required
/>
<label htmlFor="phone">Phone:</label>
<input
id="phone"
name="phone"
type="tel"
value={formData.phone}
onChange={handleChange}
/>
<button type="submit">Register</button>
</form>
);
}
export default RegistrationForm;
Explanation:
- The
formData object stores all three field values.
- Each input has a matching
name attribute.
- The shared
handleChange() function identifies which field changed.
- The computed property
[name] updates the correct field.
- The spread operator preserves the other field values.
7. Working with Textarea
The textarea element allows users to enter longer, multiline text, such as comments, descriptions, or feedback. In React, a controlled textarea uses the value prop and an onChange handler.
import { useState } from "react";
function FeedbackForm() {
const [feedback, setFeedback] = useState("");
function handleSubmit(event) {
event.preventDefault();
console.log("Feedback:", feedback);
}
return (
<form onSubmit={handleSubmit}>
<label htmlFor="feedback">Your Feedback:</label>
<textarea
id="feedback"
value={feedback}
onChange={(event) => setFeedback(event.target.value)}
rows="5"
placeholder="Write your feedback here"
/>
<button type="submit">Send Feedback</button>
</form>
);
}
export default FeedbackForm;
Note: In React, set the initial content of an uncontrolled textarea with defaultValue, or use value for a controlled textarea. Do not use children between the textarea tags to set its value.
8. Working with Select Dropdowns
A dropdown allows users to choose an option from a list. For a controlled dropdown, React manages the selected option through the value prop on the select element.
import { useState } from "react";
function CourseForm() {
const [course, setCourse] = useState("");
function handleSubmit(event) {
event.preventDefault();
console.log("Selected Course:", course);
}
return (
<form onSubmit={handleSubmit}>
<label htmlFor="course">Choose a Course:</label>
<select
id="course"
value={course}
onChange={(event) => setCourse(event.target.value)}
required
>
<option value="">Select a course</option>
<option value="react">React JS</option>
<option value="flutter">Flutter</option>
<option value="selenium">Selenium</option>
</select>
<button type="submit">Submit</button>
</form>
);
}
export default CourseForm;
Explanation: The selected value is stored in the course state variable. The onChange handler updates that variable whenever the user selects a different course.
9. Working with Checkboxes
Checkboxes allow users to select or deselect an option, such as agreeing to terms and conditions. A controlled checkbox uses the Boolean checked property rather than the text value to represent whether it is selected.
import { useState } from "react";
function TermsForm() {
const [accepted, setAccepted] = useState(false);
function handleSubmit(event) {
event.preventDefault();
if (!accepted) {
alert("Please accept the terms and conditions.");
return;
}
alert("Form submitted successfully.");
}
return (
<form onSubmit={handleSubmit}>
<label>
<input
type="checkbox"
checked={accepted}
onChange={(event) => setAccepted(event.target.checked)}
/>
I accept the terms and conditions.
</label>
<button type="submit">Continue</button>
</form>
);
}
export default TermsForm;
Explanation: The checked property reflects the Boolean state. When the checkbox changes, event.target.checked supplies its new selected status.
10. Working with Radio Buttons
Radio buttons allow users to select one option from a group, such as a preferred contact method or payment type. Radio buttons in the same group share a common name.
import { useState } from "react";
function ContactForm() {
const [contactMethod, setContactMethod] = useState("email");
function handleSubmit(event) {
event.preventDefault();
console.log("Contact Method:", contactMethod);
}
return (
<form onSubmit={handleSubmit}>
<p>Preferred Contact Method:</p>
<label>
<input
type="radio"
name="contactMethod"
value="email"
checked={contactMethod === "email"}
onChange={(event) => setContactMethod(event.target.value)}
/>
Email
</label>
<label>
<input
type="radio"
name="contactMethod"
value="phone"
checked={contactMethod === "phone"}
onChange={(event) => setContactMethod(event.target.value)}
/>
Phone
</label>
<button type="submit">Submit</button>
</form>
);
}
export default ContactForm;
The selected radio button is determined by comparing each option's value with the current contactMethod state.
11. Form Validation in React
Form validation checks whether the entered information meets the application's requirements before the form is processed. Validation can include required fields, email formats, password length, phone number formats, and matching passwords.
HTML Built-in Validation
<input
type="email"
name="email"
required
/>
<input
type="password"
name="password"
minLength="8"
required
/>
The browser provides basic validation for supported attributes such as required, type="email", minLength, and numeric limits. These checks improve usability but do not replace server-side validation.
Custom Validation Example
import { useState } from "react";
function EmailForm() {
const [email, setEmail] = useState("");
const [error, setError] = useState("");
const [submitted, setSubmitted] = useState(false);
function handleSubmit(event) {
event.preventDefault();
const trimmedEmail = email.trim();
if (!trimmedEmail) {
setError("Email is required.");
setSubmitted(false);
return;
}
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(trimmedEmail)) {
setError("Please enter a valid email address.");
setSubmitted(false);
return;
}
setError("");
setSubmitted(true);
}
return (
<form onSubmit={handleSubmit} noValidate>
<label htmlFor="email">Email Address:</label>
<input
id="email"
type="email"
value={email}
onChange={(event) => {
setEmail(event.target.value);
setError("");
setSubmitted(false);
}}
aria-invalid={Boolean(error)}
aria-describedby={error ? "email-error" : undefined}
/>
{error && (
<p id="email-error" role="alert">{error}</p>
)}
<button type="submit">Submit</button>
{submitted && (
<p role="status">Email validation successful.</p>
)}
</form>
);
}
export default EmailForm;
Explanation: The example checks whether the email is empty and performs a basic format check. Real applications should validate submitted data on the server as well, and use validation rules appropriate to their requirements.
12. Displaying Error Messages
Helpful validation messages tell users what needs to be corrected. Store validation errors in state and display them close to the relevant field.
{error && (
<p role="alert">{error}</p>
)}
For forms with multiple fields, you can store errors in an object keyed by field name.
const [errors, setErrors] = useState({
name: "",
email: ""
});
This makes it possible to display different messages for each input. Associate error text with its field using aria-describedby and set aria-invalid when appropriate to improve accessibility.
13. Resetting a Form After Submission
After a successful submission, a form may need to clear its inputs. For controlled components, reset the state values to their initial values.
import { useState } from "react";
function MessageForm() {
const initialForm = {
name: "",
message: ""
};
const [formData, setFormData] = useState(initialForm);
function handleChange(event) {
const { name, value } = event.target;
setFormData((previousData) => ({
...previousData,
[name]: value
}));
}
function handleSubmit(event) {
event.preventDefault();
console.log("Submitted:", formData);
setFormData(initialForm);
}
return (
<form onSubmit={handleSubmit}>
<input
name="name"
value={formData.name}
onChange={handleChange}
placeholder="Your name"
required
/>
<textarea
name="message"
value={formData.message}
onChange={handleChange}
placeholder="Your message"
required
/>
<button type="submit">Send</button>
<button
type="button"
onClick={() => setFormData(initialForm)}
>
Reset
</button>
</form>
);
}
export default MessageForm;
Important: The Reset button uses type="button" so it does not submit the form. The form is reset here immediately after logging the values; in a real application, reset only after the submission succeeds.
14. Preventing Default Browser Behavior
By default, submitting an HTML form can cause the browser to navigate to another URL or reload the current page. When handling submission in a React event handler, call event.preventDefault() to prevent that behavior.
function handleSubmit(event) {
event.preventDefault();
console.log("Form handled by React");
}
This allows the application to validate input, update state, show a confirmation message, or send a request to a backend without an automatic full-page reload.
15. Handling Form Submission Asynchronously
Many forms submit data to an API. An asynchronous handler can track whether the request is in progress, prevent duplicate submissions, and display success or error feedback.
import { useState } from "react";
function ContactForm() {
const [email, setEmail] = useState("");
const [message, setMessage] = useState("");
const [status, setStatus] = useState("");
const [loading, setLoading] = useState(false);
async function handleSubmit(event) {
event.preventDefault();
setStatus("");
setLoading(true);
try {
const response = await fetch("/api/contact", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({ email, message })
});
if (!response.ok) {
throw new Error("Unable to submit the form.");
}
setStatus("Message submitted successfully.");
setEmail("");
setMessage("");
} catch (error) {
setStatus(error.message || "Something went wrong.");
} finally {
setLoading(false);
}
}
return (
<form onSubmit={handleSubmit}>
<label htmlFor="email">Email:</label>
<input
id="email"
type="email"
value={email}
onChange={(event) => setEmail(event.target.value)}
required
/>
<label htmlFor="message">Message:</label>
<textarea
id="message"
value={message}
onChange={(event) => setMessage(event.target.value)}
required
/>
<button type="submit" disabled={loading}>
{loading ? "Submitting..." : "Submit"}
</button>
{status && <p role="status">{status}</p>}
</form>
);
}
export default ContactForm;
Note: The /api/contact endpoint is an example placeholder and must be replaced with a real backend endpoint. The server should validate submitted data and enforce appropriate security measures.
16. Common Form Events in React
| Event |
Purpose |
Example |
onChange |
Responds to changes in input values or selections. |
onChange={handleChange} |
onSubmit |
Handles form submission. |
onSubmit={handleSubmit} |
onBlur |
Runs when a field loses focus. |
onBlur={validateEmail} |
onFocus |
Runs when a field receives focus. |
onFocus={handleFocus} |
onInvalid |
Responds when a form control fails native constraint validation. |
onInvalid={handleInvalid} |
17. Common Mistakes When Creating Forms
| Mistake |
Why It Is a Problem |
Solution |
Using value without onChange on an editable controlled input |
The input cannot update normally through user typing. |
Add an onChange handler that updates state. |
Initializing a controlled input with undefined |
The input may switch between controlled and uncontrolled behavior. |
Initialize text values with an empty string. |
Forgetting event.preventDefault() |
The browser may reload or navigate on submission. |
Prevent default behavior when handling submission in React. |
Using value instead of checked for checkbox state |
The checked status is not controlled correctly. |
Use a Boolean checked value. |
| Giving every field a separate change handler unnecessarily |
Creates repetitive code for similar fields. |
Use a shared handler with field names when appropriate. |
| Using a submit button for a reset or other action |
May submit the form unexpectedly. |
Use type="button" for non-submit actions. |
| Relying only on frontend validation |
Requests can bypass browser-side validation. |
Validate data on the server too. |
| Not showing validation feedback |
Users may not know how to fix invalid values. |
Display clear, accessible error messages. |
18. Best Practices for React Forms
- Use controlled components when form values need to drive UI behavior or validation.
- Use descriptive labels for all form fields.
- Choose appropriate input types, such as
email, password, tel, and number.
- Use the
required attribute where appropriate.
- Validate and trim user input according to the application's needs.
- Show useful error, loading, and success messages.
- Keep related form values in one state object when that improves clarity.
- Use
type="submit" for submission and type="button" for other actions.
- Associate labels and error messages with their respective fields.
- Validate all untrusted data on the server before processing it.
- Never store passwords or other sensitive information in logs unnecessarily.
- Disable or otherwise guard submission while a request is pending to reduce duplicate requests.
19. Mini Project: Student Registration Form
Objective: Create a student registration form that collects a student's name, email, course, and agreement to the terms and conditions. The form validates required information and displays a confirmation message after successful local validation.
Complete Code
import { useState } from "react";
function StudentRegistrationForm() {
const [formData, setFormData] = useState({
name: "",
email: "",
course: "",
acceptedTerms: false
});
const [message, setMessage] = useState("");
function handleChange(event) {
const { name, value, type, checked } = event.target;
setFormData((previousData) => ({
...previousData,
[name]: type === "checkbox" ? checked : value
}));
setMessage("");
}
function handleSubmit(event) {
event.preventDefault();
if (!formData.acceptedTerms) {
setMessage("Please accept the terms and conditions.");
return;
}
setMessage(
`Registration details validated for ${formData.name}.`
);
}
return (
<div>
<h1>Student Registration</h1>
<form onSubmit={handleSubmit}>
<label htmlFor="name">Full Name:</label>
<input
id="name"
name="name"
value={formData.name}
onChange={handleChange}
required
/>
<label htmlFor="email">Email Address:</label>
<input
id="email"
name="email"
type="email"
value={formData.email}
onChange={handleChange}
required
/>
<label htmlFor="course">Select Course:</label>
<select
id="course"
name="course"
value={formData.course}
onChange={handleChange}
required
>
<option value="">Choose a course</option>
<option value="react">React JS</option>
<option value="flutter">Flutter</option>
<option value="selenium">Selenium</option>
</select>
<label>
<input
type="checkbox"
name="acceptedTerms"
checked={formData.acceptedTerms}
onChange={handleChange}
/>
I accept the terms and conditions.
</label>
<button type="submit">Register</button>
</form>
{message && <p role="status">{message}</p>}
</div>
);
}
export default StudentRegistrationForm;
How the Project Works
- The state object stores the values of all four fields.
- The shared change handler updates text fields, the dropdown, and the checkbox.
- The form's submit handler prevents the default browser submission.
- HTML validation checks the required name, email, and course fields.
- The custom validation checks whether the user accepted the terms.
- A message appears after successful local validation.
Important: This mini project validates information in the browser only. To create a real registration system, send the validated data to a backend and perform server-side validation before storing or processing it.
20. Interview Questions and Answers
Q1. What is a form in React JS?
Answer: A form is a component that collects user information through controls such as input fields, textareas, dropdowns, checkboxes, and radio buttons.
Q2. What is a controlled component?
Answer: A controlled component is a form element whose current value is managed by React state and updated through event handlers.
Q3. What is an uncontrolled component?
Answer: An uncontrolled component stores its current value in the DOM. The value can be read when needed using FormData or a ref.
Q4. What is the purpose of the onChange event?
Answer: The onChange event responds when a user changes an input value or selection. It is commonly used to synchronize controlled form fields with React state.
Q5. Why is event.preventDefault() used in forms?
Answer: It prevents the browser's default form submission behavior when the application intends to handle submission through React.
Q6. How do you manage multiple inputs using one state object?
Answer: Give each input a name attribute and use a shared change handler with computed property names to update the corresponding state field.
Q7. How do you manage a checkbox in React?
Answer: Use the Boolean checked prop and update the state with event.target.checked.
Q8. How do you validate a form in React?
Answer: Use HTML validation attributes, custom validation logic, or a form-validation library. Always validate untrusted input on the server as well.
Q9. How do you reset a controlled form?
Answer: Set the controlled state variables back to their initial values.
Q10. What is the difference between value and defaultValue?
Answer: value controls the current value of a form element through React. defaultValue sets its initial value for an uncontrolled form element.
21. Practice Exercises
- Create a login form with username and password fields.
- Create a registration form with name, email, phone, and password fields.
- Build a feedback form using a textarea and a rating dropdown.
- Create a form with radio buttons for selecting a preferred contact method.
- Add checkbox validation for accepting terms and conditions.
- Display field-specific error messages for invalid input.
- Reset all controlled form fields after a successful submission.
- Create a form that sends information to a test backend endpoint and displays loading, success, and error states.
22. Quick Revision
- Use HTML form elements to collect user input in React.
- Use
useState() to manage controlled form values.
- Use
onChange to update input values and onSubmit to handle submission.
- Use
checked for controlled checkboxes and radio buttons.
- Use
value to control a dropdown selection.
- Use
event.preventDefault() when handling submission without the browser's default navigation.
- Validate user input and provide accessible error messages.
- Reset state when the form should be cleared.
- Validate submitted data on the server before processing it.
Conclusion
Creating Forms in React JS is a fundamental skill for building interactive web applications. By understanding controlled and uncontrolled components, managing state, handling form events, validating input, and processing submissions, developers can build reliable forms for login, registration, feedback, and data entry. Practice these concepts by building complete forms and connecting them to backend APIs when you are ready to develop production applications.
Learn React JS with JustAcademy
Explore the React JS training course to develop your understanding of components, state management, forms, event handling, and interactive web application development.
JustAcademy React JS Training
Register for React JS Course Demo
Official React Documentation