Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I control the checkbox with the filter?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[
  {
    "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?

>Solution :

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));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading