JamesLai
JamesLai

Reputation: 191

React Checkbox Hook Array

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

Answers (2)

JamesLai
JamesLai

Reputation: 191

I've managed to solve this issue through the following method:

  1. Created another useState hook for the filteredCategoryId to accept a string.
  2. Utilized the useEffect Hook to convert categoryId array into a string of comma separated values
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

Rohit Khanna
Rohit Khanna

Reputation: 723

Replacing <FormLabel component="legend">categoryId: {categoryId} with <FormLabel component="legend">categoryId: {categoryId.join()} help?

Upvotes: 0

Related Questions