I intend to filter data by selecting different checkbox through the following codes:
const movieData = [
{
title: "movie 0",
genre: ""
},
{
title: "movie 1",
genre: ["action", "thriller"]
},
{
title: "movie 2",
genre: ["comedy", "drama"]
},
{
title: "movie 3",
genre: ["comedy", "action"]
},
{ title: "movie 4", genre: "thriller" },
{
title: "movie 5",
genre: "comedy"
},
{
title: "movie 6",
genre: "action"
},
{
title: "movie 7",
genre: "drama"
}
];
const movie = [
{ genre: "thriller" },
{ genre: "comedy" },
{ genre: "action" },
{ genre: "drama" }
];
const FilterMethod01 = () => {
const [genre, setGenre] = useState([""]);
const [filteredGenre, setFilteredGenre] = useState([""]);
const handleChange = e => {
if (e.target.checked) {
setGenre([...genre, e.target.value]);
} else {
setGenre(genre.filter(id => id !== e.target.value));
}
};
useEffect(() => {
setFilteredGenre(
movieData.filter(movie =>
genre.some(category => category === movie.genre)
)
);
}, [genre]);
return (
<Fragment>
<FormControl>
<FormGroup>
{movie.map(movie => (
<FormControlLabel
control={<Checkbox onChange={handleChange} />}
label={movie.genre}
value={movie.genre}
/>
))}
</FormGroup>
</FormControl>
{filteredGenre
.map((movie, index) => (
<Card style={{ background: "lightgreen", marginBottom: "5px" }}>
<Typography gutterBottom variant="h6" noWrap>
title: {movie.title}
</Typography>
<Typography gutterBottom variant="h6" noWrap>
genre: {movie.genre}
</Typography>
</Card>
))}
</Fragment>
);
};
However, I have the following problems with this code:
All the mapped data
["movie 0", "movie 1", "movie 2", "movie 3"...]doesn't appear by default. How can I get all the mapped data to appear by default?The mapped data only filters a single string (e.g.
{genre: ""}) instead of an array of strings (e.g.{genre: ["thriller", "action"]}). How can I select the "action" checkbox to trigger "movie 1", "movie 3", & "movie 6" to appear?
#Checkout my codesandbox here.#
If there are other better practices to achieve this result, please let me know as well. Thank you so much guys!