0
0
Reactframework~30 mins

Form handling in React - Mini Project: Build & Apply

Choose your learning style9 modes available
Form handling in React
📖 Scenario: You are building a simple contact form for a website. Visitors can enter their name and email to subscribe to a newsletter.
🎯 Goal: Create a React functional component with a form that has two input fields: one for name and one for email. The form should store the input values in state variables and update them as the user types.
📋 What You'll Learn
Use React functional components and hooks
Create state variables for name and email
Add controlled input fields for name and email
Update state on input change
💡 Why This Matters
🌍 Real World
Forms are everywhere on websites for user input like signups, contact, and feedback. Handling forms correctly is essential for good user experience.
💼 Career
React developers often build interactive forms. Knowing how to manage form state and submission is a key skill in frontend development jobs.
Progress0 / 4 steps
1
Set up the React component and state variables
Create a React functional component called ContactForm. Inside it, use useState to create two state variables: name and setName initialized to an empty string, and email and setEmail initialized to an empty string.
React
Need a hint?

Use const [name, setName] = useState('') and similarly for email.

2
Add the form and input fields
Inside the ContactForm component, return a <form> element containing two controlled <input> fields: one with type="text" and value={name}, and one with type="email" and value={email}. Add onChange handlers to update name and email state variables respectively.
React
Need a hint?

Use controlled inputs with value and onChange props.

3
Add a submit button and prevent default form submission
Inside the <form>, add a <button> with type="submit" and text Subscribe. Add an onSubmit handler to the <form> that prevents the default page reload behavior by calling event.preventDefault().
React
Need a hint?

Define a function handleSubmit that calls event.preventDefault() and assign it to the form's onSubmit.

4
Display the entered name and email below the form
Below the <form>, add a <div> that shows the text Name: {name} and Email: {email} dynamically from the state variables.
React
Need a hint?

Use JSX to display the state variables inside paragraphs.