'How do I handle my pagination in ReactJS?
Below is my code to handle pagination and add prev and next buttons to my site.
const [pageNumber, setPageNumber] = useState(props.match.params.pageno);
useEffect(() => {setPageNumber(props.match.params.pageno)},[props]);
useEffect(() => {
async function fetchData() {
try {
const { data } = await axios.get('http://api.tvmaze.com/shows?page=' +pageNumber);
setShowsData(data);
setLoading(false);
} catch (e) {
console.log(e);
}
}
fetchData();
}, [ pageNumber ]);
return (
<div>
<Link className={pageNumber===0 ? 'hidden' : 'showlink'} to={`/shows/page/${parseInt(pageNumber)-1}`}>
Previous
</Link>
<Link className='showlink' to={`/shows/page/${parseInt(pageNumber)+1}`}>
Next
</Link>
</div>
);
App.css:
.hidden{
display:none;
}
How can I get this done?
I am trying to hide the Previous link when the page number is 0 as there is nothing before that. I tried the above code but it had no effect.
Solution 1:[1]
I think you have a type mismatch between pageNumber and 0. You solve for this in your next Link by calling parseInt(pageNumber). You need to do this for your className check as well. Otherwise you will never meet that condition you're checking for.
Quick refresher:
"0" === 0 // false
"0" == 0 // true
Triple equals always checks for the data type while double equals will attempt to perform type coercion on the right side value.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | PsiKai |
