I'm Still learning react hooks so bear with me; I'm writing a custom server side pagination component; then for loop through the pages to render them like so :
const [activePageNumber, setActivePageNumber] = useState(1);
for (var i = 1; i <= pages; i++) {
if (activePageNumber > 0 && i == activePageNumber)
rows.push(
<li
key={i}
className="paginate_button page-item active"
onClick={() => {
setActivePageNumber(i);
console.log(activePageNumber);
}}
>
<a className="page-link">{i}</a>
</li>
);
else
rows.push(
<li
key={i}
className="paginate_button page-item"
onClick={() => {
setActivePageNumber(i);
console.log(activePageNumber);
}}
>
<a className="page-link">{i}</a>
</li>
);
}
and the jsx as following :
<ul className="pagination">
{rows}
</ul>
the server returning 4 pages and they got rendered properly on the screen; however the problem is whenever I click any page button activePageNumber is always 1 its not changed at all.
You are building the entire html outside of
return, soiwill always default to last number for everylielement in therowslist when you try to render it inside yourulInstead you should add all this logic inside your
returnstatement.Have a look at this sandbox