Chapter 9: Working with Forms in React
Handling Form Submissions in React
Unlike traditional HTML forms that submit data directly to the server, forms in React applications typically handle submissions using JavaScript within the component itself. This allows you to control the submission process, validate user input, and update the application state accordingly.
Here's a basic example of handling form submission in React:
import React, { useState } from 'react';
function ContactForm() {
const [name, setName] = useState('');
const [email, setEmail] = useState('');
const handleSubmit = (event) => {
event.preventDefault(); // Prevent default form submission behavior
console.log('Form submitted!', { name, email });
// Here, you can perform additional actions like sending data to an API
setName('');
setEmail('');
};
return (
<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 >
);
}
In this example:
- We use the "useState" hook to manage the form's state, including the "name" and "email" fields.
- The "handleSubmit" function is triggered when the form is submitted. It prevents the default form submission behavior using "event.preventDefault()".
- Inside "handleSubmit", you can access the current state values ("name" and "email") and perform actions like logging them to the console, sending data to a server using an API call, or updating the application's state based on the submitted data.
- The form element has an "onSubmit" prop set to the "handleSubmit" function, ensuring it's called when the form is submitted.
- Each input field has an "onChange" handler that updates the corresponding state variable ("name" or "email") with the entered value, keeping the component's state in sync with user input.
- After submission, the state values are reset to clear the form.
Controlled Components for Form Inputs
In React, forms are typically implemented using controlled components. This means the form data is controlled by the React component's state, rather than by the DOM itself. This approach allows for better control over the form's behavior and validation.
Here, the input fields have a "value" attribute set to the corresponding state variable ("name" or "email"). This ensures the displayed value in the input reflects the current state. The "onChange" handler updates the state whenever the user modifies the input, maintaining consistency between the UI and the component's state.
Validating User Input
Validating user input is crucial to ensure the integrity of your application's data. React allows you to implement validation logic to check if the entered data meets specific criteria before submission.
Here are some common validation techniques:
- Inline Validation: You can display error messages directly next to the input field based on the validation rules.
- Form-Level Validation: You can display a general error message at the top of the form after submission if there are any validation errors.
- Regular Expressions: You can use regular expressions to validate
You can use regular expressions to validate specific input formats, such as email addresses, phone numbers, or passwords. Libraries like "react-hook-form" or custom validation functions can help with this process.
Example of Inline Validation:
import React, { useState } from 'react';
function RegistrationForm() {
const [name, setName] = useState('');
const [email, setEmail] = useState('');
const [errorMessage, setErrorMessage] = useState('');
const validateEmail = (email) => {
const re = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(String(email).toLowerCase());
};
const handleChange = (event) => {
const { name, value } = event.target;
if (name === 'email') {
setErrorMessage(validateEmail(value) ? '' : 'Please enter a valid email address');
}
// Update state for name or email based on event.target
};
const handleSubmit = (event) => {
event.preventDefault();
// Perform form submission logic
};
return (
<form onSubmit={handleSubmit}>
<label htmlFor="name">Name:</label>
<input type="text" id="name" value={name} onChange={handleChange} />
<label htmlFor="email">Email:</label>
<input type="email" id="email" value={email} onChange={handleChange} />
<span style={{ color: 'red' }}>{errorMessage}</span>
<button type="submit">Register</button>
</form>
);
}