To work with forms in React two approaches are to either use Controlled Components or use Uncontrolled Components (as detailed here). Swyx shares a third way of working with forms:
A lower friction way to handle form inputs is to use HTML name attributes. As a bonus, your code often turns out less React specific!
The key is to add an onchange
handler onto the form. From there you can access event.currentTarget
to get the form, and then add .nameOfTheInput
to it.
// 31 lines of code
function NameForm() {
const handleSubmit = (event) => {
event.preventDefault();
if (event.currentTarget.nameField.value === 'secretPassword') {
alert('congrats you guessed the secret password!')
} else if (event.currentTarget.nameField.value) {
alert('this is a valid submission')
}
}
const handleChange = event => {
let isDisabled = false
if (!event.currentTarget.nameField.value) isDisabled = true
if (event.currentTarget.ageField.value <= 13) isDisabled = true
event.currentTarget.submit.disabled = isDisabled
}
return (
<form onSubmit={handleSubmit} onChange={handleChange}>
<label>
Name:
<input type="text" name="nameField" placeholder="Must input a value"/>
</label>
<label>
Age:
<input type="number" name="ageField" placeholder="Must be >13" />
</label>
<div>
<input type="submit" value="Submit" name="submit" disabled />
</div>
</form>
);
}
Feels weird to manipulate the form’s submit button disabled
state directly 😅