📖 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
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
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
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
Hint
Use JSX to display the state variables inside paragraphs.
Practice
(1/5)
1. What is the main purpose of using useState in React form handling?
easy
A. To automatically validate form inputs
B. To style the form elements dynamically
C. To send form data directly to the server
D. To store and update the current value of form inputs
Solution
Step 1: Understand useState role in React
useState is used to create a state variable that holds data and can be updated.
Step 2: Connect useState to form inputs
In form handling, useState stores the current input value and updates it on user typing.
Final Answer:
To store and update the current value of form inputs -> Option D
Quick Check:
useState manages input values = A [OK]
Hint: useState holds input values and updates on change [OK]
Common Mistakes:
Thinking useState styles elements
Assuming useState sends data to server
Confusing useState with validation logic
2. Which of the following is the correct way to update state on input change in React?
easy
A. onChange={(e) => setValue(e.target.value)}
B. onChange={() => setValue(e.value)}
C. onChange={(e) => setValue(e.target)}
D. onChange={(e) => setValue(e.currentTarget)}
Solution
Step 1: Identify correct event target usage
The input value is accessed via e.target.value in event handlers.
Step 2: Confirm correct syntax for setState call
Using setValue(e.target.value) updates state with the input's current value.
Final Answer:
onChange={(e) => setValue(e.target.value)} -> Option A
Quick Check:
Use e.target.value to get input value [OK]
Hint: Use e.target.value inside onChange to update state [OK]
Common Mistakes:
Using e.value instead of e.target.value
Passing e.target or e.currentTarget directly
Omitting the event parameter e
3. What will be the output when the following React component is rendered and the user types 'Hi' in the input?
B. The paragraph shows 'Hello, Hi!' as user types 'Hi'
C. The paragraph remains empty regardless of input
D. The input clears automatically after typing
Solution
Step 1: Understand controlled input behavior
The input value is controlled by state variable 'name' which updates on change.
Step 2: Observe paragraph rendering with state
The paragraph displays 'Hello, {name}!' so it updates live as 'name' changes.
Final Answer:
The paragraph shows 'Hello, Hi!' as user types 'Hi' -> Option B
Quick Check:
Controlled input updates state and display = D [OK]
Hint: Controlled inputs update state and display live [OK]
Common Mistakes:
Expecting input to clear automatically
Thinking paragraph won't update
Assuming page reloads on input change
4. Identify the error in this React form submission handler:
function handleSubmit(e) {
alert('Submitted');
}
What is missing to prevent the page from reloading on submit?
medium
A. Call e.preventDefault() inside handleSubmit
B. Use return false at the end of handleSubmit
C. Wrap alert in a setTimeout function
D. No error, the code works fine
Solution
Step 1: Understand default form submit behavior
By default, form submission reloads the page unless prevented.
Step 2: Prevent default reload in React
Calling e.preventDefault() inside the submit handler stops the reload.
Final Answer:
Call e.preventDefault() inside handleSubmit -> Option A
Quick Check:
Use e.preventDefault() to stop reload [OK]
Hint: Always call e.preventDefault() in submit handlers [OK]
Common Mistakes:
Forgetting to pass event parameter e
Using return false instead of preventDefault
Assuming alert stops reload
5. You want to handle multiple input fields in one React form using a single state object. Which code snippet correctly updates the state for the changed input field?
const [formData, setFormData] = React.useState({ email: '', password: '' });
function handleChange(e) {
// What goes here?
}
hard
A. setFormData({ e.target.name: e.target.value });
B. setFormData({ formData[e.target.name]: e.target.value });
C. setFormData({ ...formData, [e.target.name]: e.target.value });
D. setFormData({ [e.target.value]: e.target.name });
Solution
Step 1: Understand updating nested state objects
To update one field in an object state, copy existing fields with spread operator.
Step 2: Use computed property name for dynamic key
Use [e.target.name] to dynamically update the correct field with new value.
Final Answer:
setFormData({ ...formData, [e.target.name]: e.target.value }); -> Option C
Quick Check:
Spread old state + dynamic key update = B [OK]
Hint: Use spread and [e.target.name] to update form object state [OK]
Common Mistakes:
Overwriting entire state without spreading
Using invalid object key syntax
Swapping name and value in update
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.