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
, so i
will always default to last number for every li
element in the rows
list when you try to render it inside your ul
Instead you should add all this logic inside your return
statement.
Have a look at this sandbox