How to keep the check box checked , when navigating to other page of react pagination

1.4k Views Asked by At

We are on 1st page, so I have selected all:

We are on 1st page , so i have selected all

On second page, selected all:

on2nd page selected all

Again going back to first page, now check boxes are cleared:

again going back to 1st page, now check boxes are cleared

Going to the second page again, check boxes are cleared:

again going to 2nd page, check boxes are cleared

enter image description here

enter image description here

I want to ask how to keep save the id's of the check boxes in a state, and whenever I switch back to first page, it automatically searches the element with id and mark check boxes automatically.

And if I uncheck the checkbox, it deletes the id from the state.

I am able to think about the logic, but I'm unable to code it.

Small help, will leads to solve this problem.

While switching to other pages, I am successfully saving the data, by updating the state.

// push all the unique objects (combination of previous state of selectedPayments and data from list)
setSelectedPayments((prevState) => {
            var arr = [...prevState, ...list];
            var newState = [
                ...new Map(arr.map((item) => [item.id, item])).values(),
            ];
            return newState;
});
console.log('Selected payments are', selectedPayments);

Also, removing the objects, if again the checkbox is unchecked, and updating the state

// pull all the objects , which got unChecked
setSelectedPayments((prevState) => {
            var newState = prevState.filter(function (objFromA) {
                return !list.find(function (objFromB) {
                    return objFromA.id === objFromB.id;
                });
            });
            return newState;
});

Only facing issue with keeping track of the checked boxes, I have implemented this, this is keeping track of main(parent checkbox). How to extract the ids saved and check the checkboxes when we navigate from one page to another:

let elementId = e.target.id;

if (selectedBoxes.includes(elementId)) {
        const newArray = selectedBoxes.filter((e) => e !== elementId);
        setSelectedBoxes(newArray);
} else {
        setSelectedBoxes((prevState) => {
            return [...prevState, elementId];
        });
}
1

There are 1 best solutions below

2
On

First i modified the Res Json , so that it set's a property isSelected = true, by comparing the element from the selectedPayments enter image description here

inAll check handler , i set the selectedPayments like this enter image description here

And render using this enter image description here

This is how ,i solved this problem.

** Better and improved answers are always welcome, please share your views.