When building forms in React, developers often need to handle user input efficiently. While managing state for each form field is a common approach, it can become difficult for larger forms. The FormData API offers an alternative, making it easier to collect and process form inputs without having to manually manage state for each field.
In this post, we'll explore how to use FormData in React to capture and handle user-entered data in a form submission.
To read user-entered data in a React form using FormData, you can use the FormData API, which provides a way to easily capture form data and handle it programmatically.
Step-by-Step Guide
1. Set up a form in React: Create a form where users can input data.
2. Use the onSubmit event: Attach an onSubmit handler to the form to capture the data when the form is submitted.
3. Create a FormData object: Inside the onSubmit handler, use the FormData constructor to capture the form data.
4. Access form data: You can retrieve the form data using the get() or entries() methods of the FormData object.
Example
export default function UserRegistration() {
function validateRegistrationForm(event) {
event.preventDefault();
let form = event.target;
let formData = new FormData(form);
let username = formData.get("myName");
let email = formData.get("myEmail");
alert(`User '${username}' registered successfully against the email ${email}`);
}
return (
<form method="POST" onSubmit={validateRegistrationForm}>
<label htmlFor="name">Enter your name</label>
<input id="name" name="myName" required /> <br /> <br />
<label htmlFor="email">Enter your email</label>
<input id="email" name="myEmail" required /> <br /> <br />
<button type="submit">Register</button>
</form>
);
}
In the above UserRegistration component, the FormData API is used to capture and handle user input when the form is submitted.
validateRegistrationForm
The validateRegistrationForm function is triggered when the form is submitted because it is set as the onSubmit handler for the form. This function prevents the default form submission behavior using event.preventDefault(), which ensures that the page doesn’t reload after the form is submitted.
let form = event.target;
Captures the form element that triggered the submission.
let formData = new FormData(form);
Creates a new FormData object using the form element. This FormData object automatically gathers all the input fields within the form and stores their names and values.
formData.get("myName")
This retrieves the value of the input field with the name="myName". In this case, it captures the value entered in the "name" field.
formData.get("myEmail")
This retrieves the value of the input field with the name="myEmail", which holds the user's email.
After collecting the values, the function displays an alert with the user’s name and email, indicating that the registration was successfu
Follow step-by-step procedure to build the complete working application.
Step 1: Go to the post (Quickly Set Up a React Project with Vite: A Step-by-Step), and set up a React Project ‘form_data_demo’. Project structure looks like below.
Step 2: Create components folder in src/ folder, and define UserRegistration component.
UserRegistration.jsx
export default function UserRegistration() {
function validateRegistrationForm(event) {
event.preventDefault();
let form = event.target;
let formData = new FormData(form);
let username = formData.get("myName");
let email = formData.get("myEmail");
alert(`User '${username}' registered successfully against the email ${email}`);
}
return (
<form method="POST" onSubmit={validateRegistrationForm}>
<label htmlFor="name">Enter your name</label>
<input id="name" name="myName" required /> <br /> <br />
<label htmlFor="email">Enter your email</label>
<input id="email" name="myEmail" type="email" required /> <br /> <br />
<button type="submit">Register</button>
</form>
);
}
Step 3: Update main.jsx file like below.
main.jsx
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import UserRegistration from './components/UserRegistration'
createRoot(document.getElementById('root')).render(
<StrictMode>
<UserRegistration />
</StrictMode>,
)
Step 4: Build and run the Application by executing below commands.
cd form_data_demo npm install npm run dev
Open the url ‘http://localhost:5173/ on browser, you will see below screen.
Enter you name and email, click on Register button, you will get registration successful message.
You can download this application from this link.
No comments:
Post a Comment