Reputation: 191
I have the following data:
const data = [
{
categoryId: 20
},
{
categoryId: 21
},
{
categoryId: 28
},
{
categoryId: 16
},
{
categoryId: 10
}
];
And this is my code below:
const Demo01 = () => {
const [categoryId, setCategoryId] = useState([]);
const handleCategory = (e, value) => {
if (e.target.checked) {
setCategoryId([...categoryId, e.target.value]);
} else {
setCategoryId(categoryId.filter((id) => id !== e.target.value));
}
};
return (
<FormControl component="fieldset">
<FormLabel component="legend">categoryId: {categoryId}</FormLabel>
<FormGroup row>
{data.map((xxx) => (
<FormControlLabel
control={
<Checkbox
color="primary"
value={xxx.categoryId}
onChange={handleCategory}
/>
}
label={xxx.categoryId}
labelPlacement="end"
/>
))}
</FormGroup>
</FormControl>
);
};
I want to use checkboxes to add or remove categoryId data within an array. However, the results I'm getting when checking all these boxes are:
2021281610
I want my categoryId array to be separated with commas as follow:
20,21,28,16,10
How can I resolve this issue above? You can also checkout my CODESANDBOX HERE for more details
Note: I've already tried other methods here but it didn't work for me.
EDIT: I want my categoryId array to be a string of (comma separated) array values. I've tried .toString() & .join() method but it didn't work.
Upvotes: 1
Views: 1263
Reputation: 191
I've managed to solve this issue through the following method:
const [categoryId, setCategoryId] = useState([]);
const [filteredCategoryId, setFilteredCategoryId] = useState("");
const handleCategory = (e, value) => {
if (e.target.checked) {
setCategoryId([...categoryId, e.target.value]);
} else {
setCategoryId(categoryId.filter((id) => id !== e.target.value));
}
};
useEffect(() => {
if (categoryId.length === 0) {
setFilteredCategoryId("");
} else {
setFilteredCategoryId(categoryId.join(","));
}
}, [categoryId]);
I can only use the .toString() or .join() method after using the hook above. CODESANDBOX here
Upvotes: 2
Reputation: 723
Replacing <FormLabel component="legend">categoryId: {categoryId}
with <FormLabel component="legend">categoryId: {categoryId.join()}
help?
Upvotes: 0