React-Formulare ohne State
Problem
export const RegistrationForm = ({ submitForm }) => {
const [name, setName] = useState('');
const [email, setEmail] = useState('');
return (
<form onSubmit={() => submitForm(name, email)}>
<label>
<b>Name: </b>
<input value={name} onChange={(e) => setName(e.currentTarget.value)} />
</label>
<label>
<b>E-Mail: </b>
<input value={email} onChange={(e) => setEmail(e.currentTarget.value)} />
</label>
<button type="submit">Submit</button>
</form>
);
};
Lösung
export const RegistrationForm = ({ submitForm }) => (
<form onSubmit={(e) => submitForm(new FormData(e.currentTarget))}>
<label><b>Name: </b><input name="name" /></label>
<label><b>E-Mail: </b><input name="email" /></label>
<button type="submit">Submit</button>
</form>
);
function submitFormExample(formData: FormData) {
formData.forEach((value, key) => console.log(key, value));
for(const [key, value] of formData) { console.log(key, value); }
fetch("/api/register", { body: formData, ... }).then(...);
}
Weiterführende Aspekte
- Dokumentation zu FormData: https://developer.mozilla.org/en-US/docs/Web/API/FormData
---
Autor: Santo Pfingsten / Software Engineer / Standort Leipzig
Zum ToiletPaper #138: React-Formulare ohne State (PDF)
Lust, das nächste ToiletPaper zu schreiben? Jetzt bei jambit bewerben!