Home > Software engineering >  How to dynamically filter data base on category property ReactJS
How to dynamically filter data base on category property ReactJS

Time:08-15

I am trying to filter data based on categories but have encountered some difficulties. I want to have a list of items that represent the categories on the side and on the other side all of the items. When the users click on the specific categories only the items that have that particular category should be rendered. Here is what I have so far: codesandbox The first problem I have encountered is that in the data file are more items with the same categories, and if I map through them, the same categories would show multiple times.

The second problem is that I cannot figure out how I could render only the selected categories. I would like to achieve this without a selection and the use of e.target.value.

Forward on I would like for the user to be able to select multiple categories at once and also to be able to deselect all of them.

Please let me know if my approach is current and if I need to restructure my data. Also, I would appreciate it if you could link the responses to some threads that are similar.

CodePudding user response:

You can create a function which will return unique catergory as:

function getUniqueCategory(books) {
    const set = new Set();
    return books.filter((o) => {
        return set.has(o.category) ? false : (set.add(o.category), true);
    });
}

CODESANDBOX DEMO

and onClick of category you can pass listItem as:

onClick={() => sortList(listItem)}>

and Filter list as:

const sortList = (listItem) => {
    console.log(listItem);

    const categoryGroup = books.filter((obj) => {
        return obj.category === listItem.category;
    });

    setFilteredList(categoryGroup);
};
  • Related