Home > Blockchain >  How do I handle my pagination in ReactJS?
How do I handle my pagination in ReactJS?

Time:03-05

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.

CodePudding user response:

You also do condition rendering for pageNumber like,

{ pageNumber !== 0 && <Link>{your code}</Link> }

For this condition also you've to check the type of your datatype like string is coming in pageNumber and you're comparing with int then this code does not have any effect.

Using this conditional rendering you don't have to rely on the CSS part this will to conditional rendering which is handled by javascript.

CodePudding user response:

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.

  • Related