Reputation: 1956
I'm trying to set all items checked by default when the component first renders.
From docs, there is a property defaultChecked
, but the setting as a true
doesn't help.
Also, it doesn't work with checked
property.
Here is the demo link and code example
import React, { useState } from "react";
import InputLabel from "@mui/material/InputLabel";
import Checkbox from "@mui/material/Checkbox";
import ListItemIcon from "@mui/material/ListItemIcon";
import ListItemText from "@mui/material/ListItemText";
import MenuItem from "@mui/material/MenuItem";
import FormControl from "@mui/material/FormControl";
import Select from "@mui/material/Select";
import { MenuProps, useStyles, options } from "./utils";
function App() {
const classes = useStyles();
const [selected, setSelected] = useState([]);
const isAllSelected =
options.length > 0 && selected.length === options.length;
const handleChange = (event) => {
const value = event.target.value;
if (value[value.length - 1] === "all") {
setSelected(selected.length === options.length ? [] : options);
return;
}
setSelected(value);
};
console.log("selected", selected);
return (
<FormControl className={classes.formControl}>
<InputLabel id="mutiple-select-label">Multiple Select</InputLabel>
<Select
labelId="mutiple-select-label"
multiple
value={selected}
onChange={handleChange}
renderValue={(selected) =>
!isAllSelected ? selected.join(", ") : "alle"
}
MenuProps={MenuProps}
>
<MenuItem
value="all"
classes={{
root: isAllSelected ? classes.selectedAll : ""
}}
>
<ListItemIcon>
<Checkbox
defaultChecked
classes={{ indeterminate: classes.indeterminateColor }}
//checked={isAllSelected}
// indeterminate={
// selected.length > 0 && selected.length < options.length
// }
/>
</ListItemIcon>
<ListItemText
classes={{ primary: classes.selectAllText }}
primary="Select All"
/>
</MenuItem>
{options.map((option) => (
<MenuItem key={option} value={option}>
<ListItemIcon>
<Checkbox
defaultChecked
//checked={selected.indexOf(option) > -1}
/>
</ListItemIcon>
<ListItemText primary={option} />
</MenuItem>
))}
</Select>
</FormControl>
);
}
export default App;
Any help will be appreciated
Upvotes: 1
Views: 2497
Reputation: 13
https://mui.com/components/checkboxes/
You don't set defaultChecked to anything, you just pass it to the component:
<Checkbox defaultChecked />
Side note: It might be a good idea to upgrade to v5 of MUI. Looks like you're using the old v4 or earlier packages. (material-ui is the old package naming convention)
https://mui.com/guides/migration-v4/
Upvotes: 1