Keep an input's text in state, enable the button only for a valid email, and handle the submit.
React · beginner · 8 min · 23 steps · free
import { useState } from 'react';
export default function SignupForm() {
const [email, setEmail] = useState('');
const [sent, setSent] = useState(false);
function handleSubmit(e) {
e.preventDefault();
setSent(true);
}
if (sent) {
return <p>Thanks! We will write to {email}.</p>;
}
return (
<form onSubmit={handleSubmit}>
<input value={email} onChange={(e) => setEmail(e.target.value)} placeholder="Email" />
<button disabled={!email.includes('@')}>Sign up</button>
</form>
);
}<SignupForm> for the first time: it calls the SignupForm function.useState runs for the first time, so React stores the starting value for email and returns it: "".useState runs for the first time, so React stores the starting value for sent and returns it: false.sent is false, so the if-block is skipped.email, and every change goes through onChange.onChange handler.e.target.value is what is now in the box: "ada@example.com".<SignupForm> again (render 2): it calls SignupForm once more, from the top.useState returns the value React has kept for email: "ada@example.com". The starting value is only used on the first render.useState returns the value React has kept for sent: false. The starting value is only used on the first render.sent is false, so the if-block is skipped.SignupForm returns JSX: a description of what the screen should show, <form>…</form>. React has not changed the page yet.handleSubmit.e.preventDefault() stops the browser's default action for a form: reloading the page.setSent(true) does not change sent right away: React queues the update and will render again. In this call sent is still false.<SignupForm> again (render 3): it calls SignupForm once more, from the top.useState returns the value React has kept for email: "ada@example.com". The starting value is only used on the first render.useState returns the value React has kept for sent: true. The starting value is only used on the first render.sent is true now, so the component returns the thank-you message early.SignupForm returns JSX: a description of what the screen should show, <p>Thanks! We will write to ada@example.com.</p>. React has not changed the page yet.Answer: Read-only. React keeps resetting it to email.
Answer: e.target.value
← Lifting State Up · useEffect: Code That Runs After Render →