Skip to content

Instantly share code, notes, and snippets.

@geekelo
Created January 4, 2024 07:51
Show Gist options
  • Save geekelo/08f900c5be22f5ec784ec8a24d481320 to your computer and use it in GitHub Desktop.
Save geekelo/08f900c5be22f5ec784ec8a24d481320 to your computer and use it in GitHub Desktop.
Load More | Load Less Algorithm (React.js)
const personnels = useSelector((state) => state.display_personnel.value);
const [itemsToShow, setItemsToShow] = useState(12);
// HANDLE PAGINATION
const handleLoadMore = (e) => {
e.preventDefault();
setItemsToShow(itemsToShow + 12);
};
const handleLoadLess = (e) => {
e.preventDefault();
setItemsToShow(Math.max(itemsToShow - 12, 12));
};
if (personnels.length > 0) {
const personnel = [...personnels].sort((a, b) => b.id - a.id);
const displayedPersonnel = personnel
.slice(0, itemsToShow);
return (
<div className="load-more-container">
{itemsToShow < personnel.length && (
<button type="submit" className="paginate" onClick={handleLoadMore}>
Load More ▼
</button>
)}
{itemsToShow > 12 && (
<button type="submit" className="paginate" onClick={handleLoadLess}>
Load Less ▲
</button>
)}
</div>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment