Created
February 27, 2025 02:41
-
-
Save felipe-b-oliveira/84f3d31e82261539f9ff0cc69e01c6ff to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useState } from "react"; | |
import { Checkbox, Stack } from "@mui/material"; | |
const options = [ | |
{ label: "Todos", value: "all" }, | |
{ label: "Opção 1", value: "option1" }, | |
{ label: "Opção 2", value: "option2" }, | |
{ label: "Opção 3", value: "option3" }, | |
]; | |
export default function CheckboxList() { | |
const [selected, setSelected] = useState<string[]>(options.map((opt) => opt.value)); | |
const handleChange = (value: string) => { | |
if (value === "all") { | |
setSelected((prev) => | |
prev.length === options.length ? [] : options.map((opt) => opt.value) | |
); | |
} else { | |
const newSelected = selected.includes(value) | |
? selected.filter((item) => item !== value) | |
: [...selected, value]; | |
setSelected(newSelected.length === options.length - 1 ? options.map((opt) => opt.value) : newSelected); | |
} | |
}; | |
return ( | |
<Stack spacing={1}> | |
{options.map(({ label, value }) => ( | |
<Stack key={value} direction="row" alignItems="center" spacing={1}> | |
<Checkbox | |
checked={selected.includes(value)} | |
onChange={() => handleChange(value)} | |
/> | |
<label>{label}</label> | |
</Stack> | |
))} | |
</Stack> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment