jeudi 20 août 2020

Arranging the checkbox items belonging to same category into one section

With my e-commerce requirements, I have a filter that consists of multiple checkboxes. The user selects one or multiple checkboxes to filter the list of items in a table.

The checkboxes arrangement looks something like this (sample):

Mathematics
  maths checkbox1
  maths checkbox2
  maths checkbox3

Physics
  phy checkbox1
  phy checkbox2
  phy checkbox3
  

As any of the filters(checkboxes) are selected, the filters have to be displayed in a component, like this:

enter image description here

With some workaround, I was able to implement a single array containing the selected filter but not sure how to handle this particular way of grouping filters belonging to a same category.

Tried so far:

 initialstate = {
       filters: [
            {
                title: '',
                options: [
                    {
                        name: '',
                        key: '',
                        label: '',
                    }
                ],
            }
        ],
       selected: []
    }

const setFilters = (value) => {

setFilterOptions((state) => {

    const selectedFilters = state.selected.find(
        (obj) => obj === value
    );

    const selected = selectedFilters
        ? state.selected.filter(
            (obj) => obj !== value
        )
        : [...state.selected, value];


    return {
        selected,
        filters: [
            ...state.filters.map((filter) => {
                return {
                    ...filter,
                    options: filter.options.map((ele) => {
                        return {
                            ...ele,
                            checked: selected.includes(ele.label)
                        };
                    })
                };
            })
        ]
    };
});

};

The algo that I could think of:

  1. function setFilters(value) takes the label of the filter selected.
  2. component state:

const [filterOptions, setFilterOptions] = useState(initialState);

  1. inside this function, loop over the state.selected array of objects and check to which category the value belongs.
  2. if the value does not exist for that category, add it an array. If it already exists (for the same category), then push it to the respective array.
  3. map over the final array to render the names of the filters (as in picture).

I am a bit confused about how to implement this logic actually.

Need a bit help to implement this in the best possible way.

Thank you in advance.




Aucun commentaire:

Enregistrer un commentaire