Home > Software design >  How do I control the checkbox with the filter?
How do I control the checkbox with the filter?

Time:12-20

I want to make a controllable checkbox that has checked becomes true if the post id is the same as the id from another array, but I don't understand how to do it. When you click on the checkbox, the post id is added to the bookmark array, so I want to make it controllable

The array with the id I get from the redux store:

const bookmarksData = useSelector((state) => state.bookmark.bookmarksData);

the array looks like this:

[
  {
    "id": 5
  },
  {
    "id": 2
  },
  {
    "id": 19
  },
  {
    "id": 22
  },
  {
    "id": 23
  },
  {
    "id": 21
  }
]

The posts I display with map and in the loop I tried to add a filter function to the checked, which would look for matching id and if they are, then put it in true, but after this function all checked became true. I don't really understand what the problem is, why all the posts became checked true

//code outside the loop
const setChecked = (idS) => {
   bookmarksData.filter((e) => e.id === idS) ? true : false
 }

//the code in the loop where I display the posts
<Checkbox
                  icon={<BookmarkBorderIcon />}
                  checkedIcon={<BookmarkIcon />}
                  checked={() => setChecked(id)}
                  onClick={() => savedBokmark({ id })}
 />

enter image description here

Can you tell me what the problem is and how to make the checkbox work properly with filtering?

CodePudding user response:

You need to set the boolean directly.

checked={setChecked(id)}

also in the setChecked function you can do the following modification. else when there is no matched elements it returns empty array which will still be true.

const setChecked = (idS) => Boolean(bookmarksData.find((e) => e.id === idS));

CodePudding user response:

checked prop in Checkbox component expects a boolean value, so you can do it like this

//the code in the loop where I display the posts

<Checkbox
                  icon={<BookmarkBorderIcon />}
                  checkedIcon={<BookmarkIcon />}
                  checked={setChecked(id)}
                  onClick={() => savedBokmark({ id })}
 />
  • Related