Complete the code to prevent the default form submission behavior.
function MyForm() {
const handleSubmit = (event) => {
event.[1]();
alert('Form submitted!');
};
return (
<form onSubmit={handleSubmit}>
<button type="submit">Submit</button>
</form>
);
}Calling event.preventDefault() stops the browser from reloading the page on form submission.
Complete the code to update the state when the input value changes.
import { useState } from 'react'; function MyForm() { const [name, setName] = useState(''); return ( <form> <input type="text" value={name} onChange={e => setName([1])} /> </form> ); }
The input's current value is accessed via e.target.value in the event handler.
Fix the error in the form submission handler to correctly log the input value.
import { useState } from 'react'; function MyForm() { const [email, setEmail] = useState(''); const handleSubmit = (event) => { event.preventDefault(); console.log([1]); }; return ( <form onSubmit={handleSubmit}> <input type="email" value={email} onChange={e => setEmail(e.target.value)} /> <button type="submit">Send</button> </form> ); }
The current input value is stored in the email state variable, so logging email shows the input.
Fill both blanks to create a controlled input that updates state and prevents default form submission.
import { useState } from 'react'; function MyForm() { const [text, setText] = useState(''); const handleSubmit = (event) => { event.[1](); alert(text); }; return ( <form onSubmit={handleSubmit}> <input value={text} onChange={e => setText(e.[2])} /> <button type="submit">Go</button> </form> ); }
Use event.preventDefault() to stop form reload and e.target.value to get input changes.
Fill all three blanks to create a form that updates two inputs and logs their values on submit.
import { useState } from 'react'; function MyForm() { const [firstName, setFirstName] = useState(''); const [lastName, setLastName] = useState(''); const handleSubmit = (event) => { event.[1](); console.log(`Full name: ${firstName} [2] ${lastName}`); }; return ( <form onSubmit={handleSubmit}> <input value={firstName} onChange={e => setFirstName(e.[3])} placeholder="First Name" /> <input value={lastName} onChange={e => setLastName(e.target.value)} placeholder="Last Name" /> <button type="submit">Submit</button> </form> ); }
Use event.preventDefault() to stop reload, + to join names, and e.target.value to update state.