Skip to content

Instantly share code, notes, and snippets.

@felipe-b-oliveira
Created February 27, 2025 02:41
Show Gist options
  • Save felipe-b-oliveira/84f3d31e82261539f9ff0cc69e01c6ff to your computer and use it in GitHub Desktop.
Save felipe-b-oliveira/84f3d31e82261539f9ff0cc69e01c6ff to your computer and use it in GitHub Desktop.
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