I am using below code for pagination.
<ul className="pagination">
<li className="page-item">
<button className="page-link btn btn-success btn-block" onClick={prev} >Previous</button>
</li>
<li className="page-item">
<button className="page-link btn btn-success btn-block " onClick={next}>Next</button>
</li>
</ul>
const next = () => {
if (page <= lastPage) {
setPage(page 1);
}
}
const prev = () => {
if (page > 1) {
setPage(page - 1);
}
}
my requirement is when data of first page
is getting displayed then prev
button should be disabled. when data of lastpage
is getting displayed then next
button should be disabled.
I mean if(page==1)
disableprev
and if(page==lastPage)
disable next
.how can I do it?
CodePudding user response:
You can conditionally disable a button using an expression on the disabled
property of the button. For example, for the Previous Button, you can do this,
<button disabled={page == 1} className="page-link btn btn-success btn-block" onClick={prev} >Previous</button>
You can follow the same thing for the Next button too. Just change the expression to page == lastPage
But make sure that the page
property is a state of the component so that React automatically refreshes the component when it changes. Regarding your use of setPage
I suppose it's already the case
CodePudding user response:
You can implement other methods like disabling the button on page load or something like that, but if you want to keep it simple just add alerts.
NOTE: You had a bug in the first conditional because if you have 50 pages and the actual page is 50, the condition (page <= lastpage)
will be true and you will send the user to the page 51 that doesn't exist.
const next = () => {
if (page < lastPage) {
setPage(page 1);
} else {
alert("This is the last page");
}
}
const prev = () => {
if (page > 1) {
setPage(page - 1);
} else {
alert("This is the first page");
}
}
<ul className="pagination">
<li className="page-item">
<button className="page-link btn btn-success btn-block" onClick={prev}>Previous</button>
</li>
<li className="page-item">
<button className="page-link btn btn-success btn-block " onClick={next}>Next</button>
</li>
</ul>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>