Making Forms Even Cooler with React
What Are Controlled Components?
In React, we like to keep everything in check. A "controlled component" means React is in control of what's happening in the form. It helps us manage things more easily.
Adding More Fun: Checkboxes and Radio Buttons
Let's make our form more interesting! We can add checkboxes for subscribing to a newsletter and radio buttons for selecting gender.
// Imagine this is added to SimpleForm.js
// ...
const [subscribe, setSubscribe] = useState(false);
const [gender, setGender] = useState('');
// ...
<label>
Subscribe to newsletter:
<input
type="checkbox"
checked={subscribe}
onChange={() => setSubscribe(!subscribe)}
/>
</label>
<br />
<label>
Gender:
<label>
<input
type="radio"
name="gender"
value="male"
checked={gender === 'male'}
onChange={() => setGender('male')}
/>{' '}
Male
</label>
<label>
<input
type="radio"
name="gender"
value="female"
checked={gender === 'female'}
onChange={() => setGender('female')}
/>{' '}
Female
</label>