I'm struggling to create multiple Checkbox filtering in React with Material-UI. The difficult is that checkbox options are created dynamically from received data and should be split by each type of Select components
But I can't properly create states to manage them in the App.
Any ideas how to do it correctly?
Options Component
function filterDuplicate(arr) {
return arr.filter((elem, index, array) => array.indexOf(elem) === index);
}
export default function Options({ stat }) {
const [form, setForm] = useState({
publicationType: "",
termType: "",
reportGroup: "",
reportState: "",
reportFormat: ""
});
const publicationTypes = filterDuplicate(
stat.map((data) => data.publicationType)
);
const termTypes = filterDuplicate(stat.map((data) => data.termType));
const reportGroups = filterDuplicate(stat.map((data) => data.reportGroup));
const reportStates = filterDuplicate(stat.map((data) => data.reportState));
const reportFormats = filterDuplicate(stat.map((data) => data.reportFormat));
function handleSubmit(e) {
e.preventDefault();
console.log(form);
}
return (
<>
<form onSubmit={handleSubmit} className="options">
<Select type="Publication type" options={publicationTypes} />
<Select type="Term type" options={termTypes} />
<Select type="Report group" options={reportGroups} />
<Select type="Status" options={reportStates} />
<Select type="File Type" options={reportFormats} />
<Button variant="contained" color="secondary" type="submit">
RESET
</Button>
</form>
</>
);
}
Options.propTypes = {
stat: PropTypes.arrayOf(PropTypes.shape({})).isRequired
};
Select Component
export default function Select({ type, options }) {
const [check, setCheck] = useState([]);
const [value, setValue] = useState("");
const classes = useStyles();
const handleChange = (e) => {
if (e.target.checked) {
setCheck([...check, e.target.value]);
} else {
setCheck(check.filter((id) => id !== e.target.value));
}
const str = check.join(", ");
setValue(str);
};
return (
<>
<FormControl className={classes.formControl}>
<InputLabel id="select-label" className={classes.label}>
{type}
</InputLabel>
<MaterialSelect labelId="select-label" id="input-select">
{options.map((option) => (
<Checkbox option={option} key={option} onChange={handleChange} />
))}
</MaterialSelect>
</FormControl>
</>
);
}
Checkbox Component
const Checkbox = React.forwardRef(({ option, onChange }, ref) => {
return (
<div ref={ref}>
<FormControlLabel
control={<MaterialCheckbox onChange={onChange} color="primary" />}
label={option}
value={option}
/>
</div>
);
});
Checkbox.propTypes = {
option: PropTypes.string.isRequired,
onChange: PropTypes.func.isRequired
};
export default Checkbox;
https://codesandbox.io/s/checkbox-filter-vqex7?file=/src/Options.js:0-1593
Aucun commentaire:
Enregistrer un commentaire