Introduction to React Forms
Forms play a vital role in web development, allowing users to input data and perform actions on a website. In React, forms are created using the form
element and various form input elements such as input
, select
, textarea
, etc.
Forms in React are special because they utilize the concept of controlled components, where form input elements are controlled by state.

React forms enable us to create powerful, interactive user experiences by capturing and managing user input. With the help of React's useState hook, we can define state variables to hold the user input values and update them as the user interacts with the form.
Here's an example of a simple registration form component in React:
1// RegistrationForm.tsx
2
3// Import React and useState from 'react'
4import React, { useState } from 'react';
5
6// Define the RegistrationForm component
7const RegistrationForm = () => {
8 // Create state variables to hold the form input values
9 const [fullName, setFullName] = useState('');
10 const [email, setEmail] = useState('');
11 const [password, setPassword] = useState('');
12
13 // Handle form submission
14 const handleSubmit = (e) => {
15 e.preventDefault();
16 // Perform form validation and submission logic here
17 }
18
19 // Render the registration form
20 return (
21 <div>
22 <h2>Registration Form</h2>
23 <form onSubmit={handleSubmit}>
24 <label htmlFor="fullName">Full Name:</label>
25 <input type="text" id="fullName" value={fullName} onChange={(e) => setFullName(e.target.value)} />
26
27 <label htmlFor="email">Email:</label>
28 <input type="email" id="email" value={email} onChange={(e) => setEmail(e.target.value)} />
29
30 <label htmlFor="password">Password:</label>
31 <input type="password" id="password" value={password} onChange={(e) => setPassword(e.target.value)} />
32
33 <button type="submit">Register</button>
34 </form>
35 </div>
36 );
37}
38
39// Export the RegistrationForm component
40export default RegistrationForm;
In this example, we use the useState
hook to create state variables for each form input field (full name, email, and password). The value
prop of each input element is set to the corresponding state variable, and the onChange
event is used to update the state variable as the user enters input.
Try running the code and see how the form behaves! Feel free to customize the form fields and add your own validation and submission logic.
Keep in mind that React forms offer a flexible and extensible way to capture and manage user input in your applications. They are an essential aspect of building interactive user interfaces in React.
xxxxxxxxxx
export default RegistrationForm;
import React, { useState } from 'react';
const RegistrationForm = () => {
const [fullName, setFullName] = useState('');
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const handleSubmit = (e) => {
e.preventDefault();
// perform form validation and submission logic here
}
return (
<div>
<h2>Registration Form</h2>
<form onSubmit={handleSubmit}>
<label htmlFor="fullName">Full Name:</label>
<input type="text" id="fullName" value={fullName} onChange={(e) => setFullName(e.target.value)} />
<label htmlFor="email">Email:</label>
<input type="email" id="email" value={email} onChange={(e) => setEmail(e.target.value)} />
<label htmlFor="password">Password:</label>
<input type="password" id="password" value={password} onChange={(e) => setPassword(e.target.value)} />
<button type="submit">Register</button>
</form>
</div>
);
Try this exercise. Click the correct answer from the options.
Which of the following is not a best practice for React forms?
Click the option that best answers the question.
- Using controlled components
- Validating form input
- Mutating the state directly
- Handling form submission
Creating a Basic Form
To build a basic form with input fields in React, we can make use of the form
element and various form input elements such as input
, select
, textarea
, etc.
Let's start by creating a simple form component called BasicForm
that consists of two input fields: Name and Email.
1import React, { useState } from 'react';
2
3const BasicForm = () => {
4 const [name, setName] = useState('');
5 const [email, setEmail] = useState('');
6
7 const handleSubmit = (e) => {
8 e.preventDefault();
9 // Perform form validation and submission logic here
10 }
11
12 return (
13 <div>
14 <h2>Basic Form</h2>
15 <form onSubmit={handleSubmit}>
16 <label htmlFor='name'>Name:</label>
17 <input type='text' id='name' value={name} onChange={(e) => setName(e.target.value)} />
18
19 <label htmlFor='email'>Email:</label>
20 <input type='email' id='email' value={email} onChange={(e) => setEmail(e.target.value)} />
21
22 <button type='submit'>Submit</button>
23 </form>
24 </div>
25 );
26}
27
28export default BasicForm;
In the code above, we import the necessary dependencies and define the BasicForm
component. Inside the component, we initialize state variables name
and email
using the useState
hook.
The form has an onSubmit
event listener that calls the handleSubmit
function when the form is submitted. In this function, you can perform any form validation or submission logic.
Each input field has a corresponding state variable (name
and email
) and an onChange
event listener that updates the state when the user enters input.
Try implementing the BasicForm
component and see how it renders a basic form with input fields for Name and Email!
xxxxxxxxxx
export default BasicForm;
// Import React and useState from 'react'
import React, { useState } from 'react';
// Define the BasicForm component
const BasicForm = () => {
// Create state variables to hold the form input values
const [name, setName] = useState('');
const [email, setEmail] = useState('');
// Handle form submission
const handleSubmit = (e) => {
e.preventDefault();
// Perform form validation and submission logic here
}
// Render the basic form
return (
<div>
<h2>Basic Form</h2>
<form onSubmit={handleSubmit}>
<label htmlFor='name'>Name:</label>
<input type='text' id='name' value={name} onChange={(e) => setName(e.target.value)} />
<label htmlFor='email'>Email:</label>
<input type='email' id='email' value={email} onChange={(e) => setEmail(e.target.value)} />
<button type='submit'>Submit</button>
</form>
</div>
Let's test your knowledge. Click the correct answer from the options.
What is the purpose of the onSubmit
event listener in a form in React?
Click the option that best answers the question.
- To trigger form validation
- To capture user input
- To handle form submission
- To reset the form
Handling User Input
In React forms, capturing and managing user input in form fields is a crucial task. This allows us to collect data from users and perform actions based on their input.
Controlled Components
React uses the concept of controlled components
to handle user input. In a controlled component, the value of the input fields is controlled by React's state, which allows us to update and track the input data.
Let's take a look at an example:
1import React, { useState } from 'react';
2
3const UserForm = () => {
4 const [username, setUsername] = useState('');
5
6 const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
7 setUsername(e.target.value);
8 };
9
10 return (
11 <div>
12 <h2>User Form</h2>
13 <form>
14 <label htmlFor='username'>Username:</label>
15 <input
16 type='text'
17 id='username'
18 value={username}
19 onChange={handleChange}
20 />
21 </form>
22 </div>
23 );
24};
25
26export default UserForm;
In the code above, we use the useState
hook to create a state variable username
with an initial value of an empty string. The handleChange
function updates the username
state whenever the user types into the input field.
By setting the value
of the input field to the username
state and handling the onChange
event, we ensure that React controls the input value and updates it accordingly.
Form Submission
Once we have captured the user input, we might want to perform some action when the form is submitted. This can be done by handling the onSubmit
event of the form.
1const handleSubmit = (e: React.FormEvent) => {
2 e.preventDefault();
3 // Perform form submission logic
4};
By calling e.preventDefault()
, we prevent the default form submission behavior and handle the form submission ourselves. Inside the handleSubmit
function, we can perform any necessary logic, such as validating the input, making API calls, or updating the UI.
Summary
Handling user input in React forms involves using controlled components to track and update the input values. By utilizing React's state management, we can easily capture and manage user input in form fields. Additionally, we can handle the form submission event to perform any necessary actions.
Now, let's apply this knowledge and create interactive forms in React!
xxxxxxxxxx
export default UserForm;
// Replace with your code that demonstrates handling user input in React forms
import React, { useState } from 'react';
const UserForm = () => {
const [username, setUsername] = useState('');
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setUsername(e.target.value);
};
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
console.log(`Username: ${username}`);
};
return (
<div>
<h2>User Form</h2>
<form onSubmit={handleSubmit}>
<label htmlFor='username'>Username:</label>
<input
type='text'
id='username'
value={username}
onChange={handleChange}
/>
<button type='submit'>Submit</button>
</form>
Let's test your knowledge. Click the correct answer from the options.
What is the concept used in React to handle user input in forms?
Click the option that best answers the question.
- Uncontrolled Components
- Controlled Components
- Uncontrolled Inputs
- Controlled Inputs
Form Validation
In any web application, form validation plays a crucial role in ensuring that the data submitted by the user meets specific criteria. This validation helps to maintain the integrity of the data and prevent any potential security issues.
Regular Expressions
Regular expressions are a powerful tool for validating form data. They provide a flexible and concise way to define patterns that the input must match. In JavaScript, you can use the RegExp
object and its test()
method to perform regular expression matching.
Here's an example of performing email validation using a regular expression:
1// Replace the variable with your desired form input
2const email = 'example@example.com';
3
4// Regular expression to validate email
5const emailRegex = /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)*(\.[a-zA-Z]{2,})$/;
6
7// Function to validate email
8const validateEmail = (email) => {
9 return emailRegex.test(email);
10};
11
12// Example usage
13if (validateEmail(email)) {
14 console.log('Email is valid');
15} else {
16 console.log('Email is invalid');
17}
In the example above, we define a regular expression emailRegex
to validate an email address. The validateEmail()
function uses the test()
method to check if the provided email matches the defined pattern.
Custom Validation Logic
Besides regular expressions, you can also implement custom validation logic to ensure that form data meets specific criteria. This can include checking for minimum and maximum lengths, required fields, numerical values, and more.
Here's an example of custom validation logic for a password:
1// Replace the variable with your desired form input
2const password = 'password123';
3
4// Function to validate password
5const validatePassword = (password) => {
6 if (password.length < 8) {
7 return false;
8 }
9
10 // Additional validation logic...
11
12 return true;
13};
14
15// Example usage
16if (validatePassword(password)) {
17 console.log('Password is valid');
18} else {
19 console.log('Password is invalid');
20}
In this example, the validatePassword()
function checks if the password has a minimum length of 8 characters. Additional validation logic can be added as needed.
Summary
Form validation is a critical aspect of web development. Regular expressions and custom validation logic are powerful tools that allow you to enforce specific criteria on user input. By implementing validation, you can ensure data integrity and enhance the overall user experience.
xxxxxxxxxx
// Replace the variable with your desired form input
const email = 'example@example.com';
// Regular expression to validate email
const emailRegex = /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)*(\.[a-zA-Z]{2,})$/;
// Function to validate email
const validateEmail = (email) => {
return emailRegex.test(email);
};
// Example usage
if (validateEmail(email)) {
console.log('Email is valid');
} else {
console.log('Email is invalid');
}
Let's test your knowledge. Is this statement true or false?
Regular expressions are not used for form validation in React.
Press true if you believe the statement is correct, or false otherwise.
Displaying Form Errors
When working with forms in React, it's important to provide feedback to users when there are errors in their form input. Displaying clear and concise error messages can help users understand what went wrong and how to correct it.
Validating Form Input
Before displaying form errors, you need to validate the form input. There are various ways to validate form data, including using regular expressions, custom validation logic, or form validation libraries.
To validate form input, you can access the form fields' values and validate them based on specific criteria. For example, if you have a form field for a password, you can check if it meets the minimum length requirement or has at least one uppercase letter.
Once you've validated the form input, you can store the validation results, such as whether the input is valid or any specific error messages, in the component's state.
Displaying Error Messages
To display form errors, you can conditionally render an error message component based on the validation results stored in the state. Typically, you'll have an error message component that accepts an error message as a prop and renders it within a styled container.
Here's an example of displaying an error message for an invalid email address:
1import React, { useState } from 'react';
2
3const Form = () => {
4 const [email, setEmail] = useState('');
5 const [invalidEmailError, setInvalidEmailError] = useState('');
6
7 // Function to handle form submission
8 const handleSubmit = () => {
9 if (email === '') {
10 setInvalidEmailError('Email is required');
11 } else if (validateEmail(email)) {
12 setInvalidEmailError('Invalid email address');
13 } else {
14 // Submit form
15 }
16 };
17
18 // Function to validate email
19 const validateEmail = (email) => {
20 // Validation logic
21 };
22
23 return (
24 <form onSubmit={handleSubmit}>
25 <div>
26 <label htmlFor='email'>Email:</label>
27 <input
28 type='email'
29 id='email'
30 value={email}
31 onChange={(e) => setEmail(e.target.value)}
32 />
33 {invalidEmailError && (
34 <div style={{ color: 'red' }}>{invalidEmailError}</div>
35 )}
36 </div>
37 <button type='submit'>Submit</button>
38 </form>
39 );
40};
41
42export default Form;
In the example above, we have a form component that captures the user's email address. We validate the email address on form submission and display an error message if the email is invalid. The error message is conditionally rendered within a div
with a red color style.
By providing clear and descriptive error messages, you can guide users in correcting their form input and improve the overall user experience.
To continue with the next topic, click here.
Build your intuition. Fill in the missing part by typing it in.
To display form errors, you can conditionally render an error message component based on the validation results stored in the __. Typically, you'll have an error message component that accepts an error message as a prop and renders it within a styled container.
Write the missing line below.
Form Submission
After capturing and validating user input in a form, the next step is to submit the form data to a server for further processing. This is a crucial part of working with forms in React, as it allows you to interact with backend services and update the application's state based on the response.
Handling Form Submission
To handle form submission in React, you need to attach an event handler function to the form's onSubmit
event. This function will be triggered when the user clicks the submit button or presses the enter key.
When the form is submitted, you can access the form data, such as the values of input fields, using references or state management libraries like Redux or MobX. Once you have the form data, you can make an HTTP request to the server using techniques like AJAX or the Fetch API.
Here's an example of handling form submission in React:
1import React, { useState } from 'react';
2
3const Form = () => {
4 const [formData, setFormData] = useState({ name: '', email: '' });
5
6 const handleSubmit = (event) => {
7 event.preventDefault();
8
9 // Make an HTTP request to submit form data
10 fetch('/api/submit-form', {
11 method: 'POST',
12 body: JSON.stringify(formData),
13 headers: { 'Content-Type': 'application/json' },
14 })
15 .then((response) => response.json())
16 .then((data) => {
17 // Handle the response from the server
18 console.log(data);
19 })
20 .catch((error) => {
21 // Handle any errors
22 console.error(error);
23 });
24 };
25
26 const handleChange = (event) => {
27 setFormData({
28 ...formData,
29 [event.target.name]: event.target.value,
30 });
31 };
32
33 return (
34 <form onSubmit={handleSubmit}>
35 <div>
36 <label htmlFor='name'>Name:</label>
37 <input type='text' id='name' name='name' value={formData.name} onChange={handleChange} />
38 </div>
39 <div>
40 <label htmlFor='email'>Email:</label>
41 <input type='email' id='email' name='email' value={formData.email} onChange={handleChange} />
42 </div>
43 <button type='submit'>Submit</button>
44 </form>
45 );
46};
47
48export default Form;
In the example above, we have a form component that captures the user's name and email address. When the form is submitted, an HTTP POST request is made to the /api/submit-form
endpoint with the form data as the request body. The response from the server is logged to the console.
Handling form submission in React involves processing user input, making HTTP requests, and handling server responses. It's an important part of building interactive and data-driven web applications.
Build your intuition. Click the correct answer from the options.
What is the purpose of attaching an event handler function to the onSubmit
event of a form in React?
Click the option that best answers the question.
- To handle form validation
- To capture user input in form fields
- To submit the form data to a server
- To display error messages for invalid form input
Form Libraries and Tools
When it comes to handling forms in React, there are several popular libraries and tools available that can greatly simplify the process and make form development more efficient. These libraries often provide additional features, such as form validation, form state management, and form submission handling.
Let's take a look at React Hook Form, one of the widely used form libraries in the React ecosystem.
React Hook Form
React Hook Form is a powerful library that allows you to easily handle form state and validation in React. It leverages the capabilities of React hooks to provide a simple and intuitive API for managing form inputs and their validations.
Here's a basic example of using React Hook Form to create a form:
[Insert image URL here]
In the code snippet above, we import the useForm
hook from the react-hook-form
library. This hook provides us with several useful functions, such as register
for registering form inputs, handleSubmit
for handling form submission, and errors
for accessing form validation errors.
The register
function is used to register form inputs with React Hook Form. We can specify various validation rules for each input, such as required
for a required field and pattern
for a field with a specific format. The ref={register}
attribute is then added to the input element to link it with React Hook Form.
The handleSubmit
function is used to handle form submission. When the form is submitted, the onSubmit
function is called with the form data as the argument. In this example, we simply log the form data to the console.
By utilizing React Hook Form, you can greatly simplify the process of handling form inputs, managing form state, and performing form validation in your React applications.
xxxxxxxxxx
import React from 'react';
import { useForm } from 'react-hook-form';
const Form = () => {
const { register, handleSubmit, errors } = useForm();
const onSubmit = (data) => {
console.log(data);
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<div>
<label htmlFor='name'>Name:</label>
<input type='text' id='name' name='name' ref={register({ required: true })} />
{errors.name && <span>This field is required</span>}
</div>
<div>
<label htmlFor='email'>Email:</label>
<input type='email' id='email' name='email' ref={register({ required: true, pattern: /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i })} />
{errors.email && errors.email.type === 'required' && <span>This field is required</span>}
{errors.email && errors.email.type === 'pattern' && <span>Please enter a valid email address</span>}
</div>
<button type='submit'>Submit</button>
</form>
);
};
export default Form;
Let's test your knowledge. Click the correct answer from the options.
What library provides a simple and intuitive API for managing form inputs and their validations in React?
Click the option that best answers the question.
- React Router
- Axios
- Formik
- Redux
Generating complete for this lesson!