Forms: The Single Source of Truth
Mission
Manage several inputs with one state object and turn plain inputs into controlled components.
Tasks
- 1
Give
formDataits initial value: a single object withname,emailandrole. - 2
Bind the
valueof every field (inputs and the select) to the matching key offormData. - 3
Write one generic
handleChangethat uses the input'snameattribute. - 4
Update the state immutably with the spread operator.
- 5
Stop the browser from reloading the page on submit with
e.preventDefault().
import React, { useState } from 'react'; export default function RegistrationForm() { // 1. Replace null with one object that holds name, email and role const [formData, setFormData] = useState(null); const handleChange = (e) => { // 2. Implement the generic logic here }; const handleSubmit = (e) => { // 3. Prevent the page reload, then show the data alert("Submitted: " + JSON.stringify(formData)); }; return ( <div style={{ padding: '20px', fontFamily: 'sans-serif', maxWidth: '400px' }}> <h1>User Registration</h1> <form onSubmit={handleSubmit}> <div style={{ marginBottom: '10px' }}> <label>Name:</label> <input type="text" name="name" style={{ width: '100%' }} // 4. Bind value and onChange /> </div> <div style={{ marginBottom: '10px' }}> <label>Email:</label> <input type="email" name="email" style={{ width: '100%' }} // 5. Bind value and onChange /> </div> <div style={{ marginBottom: '10px' }}> <label>Role:</label> <select name="role" style={{ width: '100%' }}> <option value="developer">Developer</option> <option value="designer">Designer</option> <option value="manager">Manager</option> </select> </div> <button type="submit" style={{ width: '100%', padding: '10px', background: '#2563eb', color: 'white', border: 'none', borderRadius: '4px' }}> Register </button> </form> <div style={{ marginTop: '20px', fontSize: '0.8rem', color: '#666' }}> <strong>State preview:</strong> <pre>{JSON.stringify(formData, null, 2)}</pre> </div> </div> ); }
Requirements
0/6One state object holds name, email and role (not run yet)
Input, input and select all bind `value` to state (not run yet)
Every field has an onChange handler (not run yet)
One handler uses a computed key: [name]: value (not run yet)
Updates state immutably with the spread operator (not run yet)
Calls e.preventDefault() on submit (not run yet)
AI mentor
Reviews only the files you changed, plus the checks you missed.
Run the checks first. They are free and instant.