Let's Build a Simple Form
Key Concepts and Functions:
-
useState:
- The
useStatehook is used to create and manage the state of the form data (formData). It initializes the state with default values.
- The
-
handleChange Function:
- The
handleChangefunction is called whenever there is a change in any form input. It updates the corresponding piece of state in theformData.
- The
-
handleSubmit Function:
- The
handleSubmitfunction is triggered when the form is submitted. In this example, it prevents the default form submission behavior and logs the form data to the console. In a real application, you might send this data to a server.
- The
-
Event Handlers:
- The
onChangeevent is used to trigger thehandleChangefunction when the user types into any form input. - The
onSubmitevent is used to trigger thehandleSubmitfunction when the form is submitted.
- The
-
Input Elements:
- Input elements (
<input>) are used to collect user data. Thevalueattribute is set to the corresponding piece of state, and theonChangeattribute is set to thehandleChangefunction.
- Input elements (
Imagine a form where someone can enter their email address. In React, we use a function called useState to keep track of what the user types.
Here's the example of form that receive user email
// Imagine this is a file named SimpleForm.js
import React, { useState } from 'react';
function SimpleForm() {
// This line sets up a piece of memory to remember the email address
const [email, setEmail] = useState('');
// This function is called whenever someone types something in
const handleChange = (event) => {
// This line updates the memory with what the person typed
setEmail(event.target.value);
};
// This function is called when the form is submitted
const handleSubmit = (event) => {
// This line prevents the form from doing its usual browser stuff
event.preventDefault();
// Now you can do something with the email, like showing it on the screen
console.log('Email submitted:', email);
};
// This is what the form looks like
return (
<form onSubmit={handleSubmit}>
<label>
Email:
{/* This input field gets its value from the memory */}
<input type="text" value={email} onChange={handleChange} />
</label>
{/* This button triggers the form submission */}
<button type="submit">Submit</button>
</form>
);
}
export default SimpleForm;
**** not use this anymore ****1. Build a simple React form with multiple input fields.
First we need to create our project first.
npm create vite@latestYou can use any project name as you want.
For framework, we will use React + Typescript
After finishing set up, go to your project directory by this command
cd projectname
npm iThen we will install Material UI to styling our application like last week
npm install @mui/material @emotion/react @emotion/styledAnd start your project with
npm run devReferences:
https://agirlcodes.medium.com/the-complete-guide-to-building-react-forms-with-usestate-hook-e3d282ff0025