Working with checkboxes in React
Working with checkbox
is also carried out according to a similar principle, only instead of the value
attribute we specify the checked
attribute. If you pass true
to this attribute, the checkbox will be checked, and if false
, it will not be checked:
function App() {
return <div>
<input type="checkbox" checked={true} /> marked
<input type="checkbox" checked={false} /> not marked
</div>;
}
Typically, the checked
attribute is passed a state containing a logical value:
function App() {
const [checked, setChecked] = useState(true);
return <div>
<input type="checkbox" checked={checked} />
</div>;
}
Just like when working with inputs, if you hard-code the attribute value checked
- the checkbox state cannot be changed. For correct operation, we will change its state to the opposite value when the checkbox is changed:
function App() {
const [checked, setChecked] = useState(true);
function handleChange() {
setChecked(!checked); // invert the state
}
return <div>
<input type="checkbox" checked={checked} onChange={handleChange} />
</div>;
}
We can simplify:
function App() {
const [checked, setChecked] = useState(true);
return <div>
<input type="checkbox" checked={checked} onChange={() => setChecked(!checked)} />
</div>;
}
Let's output the checkbox state to a paragraph using the ternary operator:
function App() {
const [checked, setChecked] = useState(true);
return <div>
<input type="checkbox" checked={checked} onChange={() => setChecked(!checked)} />
<p>state: {checked ? 'marked' : 'not marked'}</p>
</div>;
}
Given a checkbox, a button and a paragraph. When clicking on the button, if the checkbox is checked, display the greeting text with the user in the paragraph, and if not checked - the farewell text.
Using three checkboxes, ask the user to select the languages they know: html, css, and js. Display the selection results for each language in separate paragraphs.