Demo
import React, { useEffect, useState } from 'react';
const PaginatedCheckboxList = () => {
const [items, setItems] = useState([]);
const [checkedItems, setCheckedItems] = useState({});
const [currentPage, setCurrentPage] = useState(1);
const [checkAll, setCheckAll] = useState(false);
const [hasSelectedItems, setHasSelectedItems] = useState(false);
const limit = 10;
const fetchItems = async (page) => {
const offset = (page - 1) * limit;
const response = await fetch(
`https://dummyjson.com/products?limit=${limit}&skip=${offset}`,
);
const data = await response.json();
setItems(data.products);
if (checkAll) {
setCheckedItems((prev) => ({
...prev,
[page]: data.products.map((item) => item.id),
}));
}
};
useEffect(() => {
fetchItems(currentPage);
}, [currentPage, checkAll]);
useEffect(() => {
const hasItems = Object.values(checkedItems).some(
(pageItems) => pageItems.length > 0,
);
setHasSelectedItems(hasItems);
}, [checkedItems]);
const handleCheckAll = () => {
const isChecked = !checkAll;
setCheckAll(isChecked);
if (isChecked) {
setCheckedItems((prev) => ({
...prev,
[currentPage]: items.map((item) => item.id),
}));
} else {
setCheckedItems({});
}
};
const handleCheckItem = (id) => {
setCheckedItems((prev) => {
const pageCheckedItems = prev[currentPage] || [];
const isChecked = pageCheckedItems.includes(id);
const updatedCheckedItems = isChecked
? pageCheckedItems.filter((itemId) => itemId !== id)
: [...pageCheckedItems, id];
if (checkAll) setCheckAll(false);
return {
...prev,
[currentPage]: updatedCheckedItems,
};
});
};
const handlePageChange = (page) => {
setCurrentPage(page);
};
const handleDownload = () => {
const selectedItems = Object.values(checkedItems).flat();
console.log('Downloading selected items:', selectedItems);
};
return (
<div>
<h1>Paginated Checkbox List</h1>
<label>
<input type="checkbox" checked={checkAll} onChange={handleCheckAll} />
Check All
</label>
<ul>
{items.map((item) => (
<li key={item.id}>
<label>
<input
type="checkbox"
checked={(checkedItems[currentPage] || []).includes(item.id)}
onChange={() => handleCheckItem(item.id)}
/>
{item.title}
</label>
</li>
))}
</ul>
<div>
<button
onClick={() => handlePageChange(currentPage - 1)}
disabled={currentPage === 1}
>
Previous
</button>
<button onClick={() => handlePageChange(currentPage + 1)}>Next</button>
</div>
{hasSelectedItems && (
<div>
<button onClick={handleDownload}>Download</button>
</div>
)}
</div>
);
};
export default PaginatedCheckboxList;