import React, { useState } from 'react'; function GreetingForm() { const [name, setName] = useState(''); return ( <form> <label htmlFor="nameInput">Name:</label> <input id="nameInput" type="text" value={name} onChange={e => setName(e.target.value)} aria-label="Name input" /> <p>Hello, {name}!</p> </form> ); } export default GreetingForm;
This component uses a controlled input where the value is tied to React state. Typing updates the state via setName, which re-renders the component and updates the displayed greeting.
function MyForm() { const handleSubmit = (event) => { // What goes here? }; return ( <form onSubmit={handleSubmit}> <button type="submit">Submit</button> </form> ); }
The method event.preventDefault() stops the form from submitting and refreshing the page. Other options either stop event bubbling or are invalid.
import React, { useState } from 'react'; function FixedInput() { const [text, setText] = useState(''); return ( <input type="text" value={text} onChange={() => setText(text)} aria-label="fixed input" /> ); } export default FixedInput;
The onChange handler uses setText(text), which sets the state to the current value, ignoring the new input. It should use e.target.value from the event.
submittedName after typing 'Anna' and clicking submit?import React, { useState } from 'react'; function SubmitName() { const [name, setName] = useState(''); const [submittedName, setSubmittedName] = useState(''); const handleSubmit = (e) => { e.preventDefault(); setSubmittedName(name); setName(''); }; return ( <form onSubmit={handleSubmit}> <input type="text" value={name} onChange={e => setName(e.target.value)} aria-label="name input" /> <button type="submit">Submit</button> <p>Submitted: {submittedName}</p> </form> ); } export default SubmitName;
On submit, submittedName is set to the current name value, which is 'Anna'. Then name is cleared, but submittedName keeps the submitted value.
Controlled components keep the input value in React state and update it on every change. Uncontrolled components rely on the DOM to hold the value and use refs to access it.