import React, { useState } from "react";
import { Checkbox, FormControl, FormControlLabel, FormLabel, Typography, Grid } from "@mui/material";
const CheckboxGroup: React.FC = () => {
// 選択された項目のIDを保持するステート
const [selectedValues, setSelectedValues] = useState<number[]>([]);
const items = [
{ id: 1, name: "Item 1" },
{ id: 2, name: "Item 2" },
{ id: 3, name: "Item 3" },
{ id: 4, name: "Item 4" },
{ id: 5, name: "Item 5" },
{ id: 6, name: "Item 6" },
{ id: 7, name: "Item 7" },
{ id: 8, name: "Item 8" },
{ id: 9, name: "Item 9" },
{ id: 10, name: "Item 10" },
{ id: 11, name: "Item 11" },
{ id: 12, name: "Item 12" },
];
const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
const value = parseInt(event.target.value, 10);
setSelectedValues((prevSelectedValues) =>
prevSelectedValues.includes(value)
? prevSelectedValues.filter((id) => id !== value) // 既に選択されていれば解除
: [...prevSelectedValues, value] // 選択されていなければ追加
);
};
return (
<div>
<FormControl component="fieldset">
<FormLabel component="legend">Select Items</FormLabel>
<Grid container>
{items.map((item) => (
<Grid item xs={2} key={item.id}>
<FormControlLabel
control={
<Checkbox
value={item.id}
checked={selectedValues.includes(item.id)}
onChange={handleChange}
/>
}
label={`Checkbox ${item.id}`}
/>
</Grid>
))}
</Grid>
</FormControl>
{selectedValues.length > 0 && (
<Typography variant="h6" component="div">
Selected Items: {selectedValues.map((id) => items.find((item) => item.id === id)?.name).join(", ")}
</Typography>
)}
</div>
);
};
export default CheckboxGroup;
More than 1 year has passed since last update.
Register as a new user and use Qiita more conveniently
- You get articles that match your needs
- You can efficiently read back useful information
- You can use dark theme