Pagination Component not rendered on UI - React

Siddharth Sinha

I am trying to implement pagination in my react application using this guide I created the Pagination.js file as instructed in the guide, but I am not able to see that on my UI, here is the screenshot of the applicationenter image description here

Here is my Search Results Page where I am implementing pagination, basically this will show the results fetched from the server based on user entered keyword and hence I want to show as paginated results. My js file corresponding to the above screenshot is:

import React from 'react';
import NavigationBar from './NavigationBar';
import SearchPageResultsStyle from "../assets/css/SearchResultsPage.css"
import Pagination from './Pagination';

class SearchResultsPage  extends React.Component{
    constructor(props) {
        super(props);
        console.log("Printing in the results component: this.props.location.state.data.keyword")
        console.log(this.props.location.state.data.keyword)
        this.state = {
            results: this.props.location.state.data.results,
            keyword: this.props.location.state.data.keyword,
            pageOfItems: []
        };
        this.onChangePage = this.onChangePage.bind(this);
    }

    onChangePage(pageOfItems) {
        // update local state with new page of items
        this.setState({pageOfItems});
    }
    render() {
        return(
            <div>
                <NavigationBar/>
                <h4 style={{textAlign:'center', color:'#1a0dab'}}>Showing search results for <span style={{fontWeight:'bold', fontStyle:'Italic'}}>'{this.state.keyword}'</span></h4>
                <hr/>
                <div className={'wrap'} style={SearchPageResultsStyle}>
                    <div className={'fleft'}>left column</div>
                    <div className={'fcenter'}>
                        <h3 style={{color:'#1a0dab'}}>Tweeter tweets text will be displayed here!!!</h3>
                        <a href={'https://google.com'}>Tweet urls will be displayed here</a>
                        <br/>
                        <div style={{display:'inline'}}>
                            <p><span style={{fontWeight:'bold', textColor:'#6a6a6a'}}>topic: </span>crime</p>
                            <p><span style={{fontWeight:'bold', textColor:'#6a6a6a'}}>city: </span>delhi</p>
                            <p><span style={{fontWeight:'bold', textColor:'#6a6a6a'}}>lang: </span>Hindi</p>
                            <p><span style={{fontWeight:'bold', textColor:'#6a6a6a'}}>Hashtags: </span></p>
                            <hr/>
                            <Pagination items={this.state.results} onChangePage={this.onChangePage}/>
                        </div>
                    </div>
                    <div className={'fright'}>right column</div>
                </div>
            </div>


        )
    }

}

export default SearchResultsPage;

My pagination.js file

import React from 'react';
import PropTypes from 'prop-types';

const propTypes = {
    items: PropTypes.array.isRequired,
    onChangePage: PropTypes.func.isRequired,
    initialPage: PropTypes.number,
    pageSize: PropTypes.number
};

const defaultProps = {
    initialPage: 1,
    pageSize: 10
};

class Pagination extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            pager: {}
        };

        // set page if items array isn't empty
        if (this.props.items && this.props.items.length) {
            this.setPage(this.props.initialPage);
        }
    }

    componentDidUpdate(prevProps, prevState) {
        // reset page if items array has changed
        if (this.props.items !== prevProps.items) {
            this.setPage(this.props.initialPage);
        }
    }

    setPage(page) {
        var { items, pageSize } = this.props;
        var pager = this.state.pager;
        
        if (page < 1 || page > pager.totalPages) {
            return;
        }

        // get new pager object for specified page
        pager = this.getPager(items.length, page, pageSize);

        // get new page of items from items array
        var pageOfItems = items.slice(pager.startIndex, pager.endIndex + 1);

        // update state
        this.setState({ pager: pager });

        // call change page function in parent component
        this.props.onChangePage(pageOfItems);
    }

    getPager(totalItems, currentPage, pageSize) {
        // default to first page
        currentPage = currentPage || 1;

        // default page size is 10
        pageSize = pageSize || 10;

        // calculate total pages
        var totalPages = Math.ceil(totalItems / pageSize);

        var startPage, endPage;
        if (totalPages <= 10) {
            // less than 10 total pages so show all
            startPage = 1;
            endPage = totalPages;
        } else {
            // more than 10 total pages so calculate start and end pages
            if (currentPage <= 6) {
                startPage = 1;
                endPage = 10;
            } else if (currentPage + 4 >= totalPages) {
                startPage = totalPages - 9;
                endPage = totalPages;
            } else {
                startPage = currentPage - 5;
                endPage = currentPage + 4;
            }
        }

        // calculate start and end item indexes
        var startIndex = (currentPage - 1) * pageSize;
        var endIndex = Math.min(startIndex + pageSize - 1, totalItems - 1);

        // create an array of pages to ng-repeat in the pager control
        var pages = [...Array((endPage + 1) - startPage).keys()].map(i => startPage + i);

        // return object with all pager properties required by the view
        return {
            totalItems: totalItems,
            currentPage: currentPage,
            pageSize: pageSize,
            totalPages: totalPages,
            startPage: startPage,
            endPage: endPage,
            startIndex: startIndex,
            endIndex: endIndex,
            pages: pages
        };
    }

    render() {
        var pager = this.state.pager;

        if (!pager.pages || pager.pages.length <= 1) {
            // don't display pager if there is only 1 page
            return null;
        }

        return (
            <div>
                <ul className="pagination">
                    <li className={pager.currentPage === 1 ? 'disabled' : ''}>
                        <button onClick={() => this.setPage(1)}>First</button>
                    </li>
                    <li className={pager.currentPage === 1 ? 'disabled' : ''}>
                        <button onClick={() => this.setPage(pager.currentPage - 1)}>Previous</button>
                    </li>
                    {pager.pages.map((page, index) =>
                        <li key={index} className={pager.currentPage === page ? 'active' : ''}>
                            <button onClick={() => this.setPage(page)}>{page}</button>
                        </li>
                    )}
                    <li className={pager.currentPage === pager.totalPages ? 'disabled' : ''}>
                        <button onClick={() => this.setPage(pager.currentPage + 1)}>Next</button>
                    </li>
                    <li className={pager.currentPage === pager.totalPages ? 'disabled' : ''}>
                        <button onClick={() => this.setPage(pager.totalPages)}>Last</button>
                    </li>
                </ul>
            </div>
        );
    }
}

Pagination.propTypes = propTypes;
Pagination.defaultProps = defaultProps;
export default Pagination;
I do not understand that why my list of items in Pagination.js file is not getting rendered. Can anybody point out what exactly is it that I am missing?

Siddharth Sinha

This is how I implemented the above library, it's really cool library. I have to add css to it, to make it look good. It is working for me now.

import React from 'react';
import NavigationBar from './NavigationBar';
import SearchPageResultsStyle from "../assets/css/SearchResultsPage.css"
import Pagination from './Pagination';

class SearchResultsPage  extends React.Component{
    constructor(props) {
        super(props);
        console.log("Printing in the results component: this.props.location.state.data.results")
        console.log(this.props.location.state.data.results)
        this.state = {
            results: this.props.location.state.data.results,
            keyword: this.props.location.state.data.keyword,
            pageOfItems: []
        };
        this.onChangePage = this.onChangePage.bind(this);
    }

    onChangePage(pageOfItems) {
        // update local state with new page of items
        this.setState({pageOfItems});
    }
    render() {

        const renderItems = this.state.pageOfItems.map((item, index) => {
            return (
                <div>
                    <h3 style={{color: '#1a0dab'}} key={index}>{item.text}</h3>
                    <a href={'https://google.com'} key={index}>{item.tweetUrl}</a>
                    <br/>
                    <p><span style={{fontWeight:'bold', textColor:'#6a6a6a'}} key={index}>topic: </span>{item.topic}</p>
                    <p><span style={{fontWeight:'bold', textColor:'#6a6a6a'}} key={index}>city: </span>{item.city}</p>
                    <p><span style={{fontWeight:'bold', textColor:'#6a6a6a'}} key={index}>lang: </span>{item.lang}</p>
                    <p><span style={{fontWeight:'bold', textColor:'#6a6a6a'}} key={index}>Hashtags: </span></p>
                    <hr/>
                </div>
            )
        })
        return (
            <div>
                <NavigationBar/>
                <h4 style={{textAlign:'center', color:'#1a0dab'}}>Showing search results for <span style={{fontWeight:'bold', fontStyle:'Italic'}}>'{this.state.keyword}'</span></h4>
                <hr/>
                <div className={'wrap'} style={SearchPageResultsStyle}>
                    <div className={'fleft'}>left column</div>
                    <div className={'fcenter'}>
                        {renderItems}
                        <Pagination items={this.state.results} onChangePage={this.onChangePage}/>
                    </div>
                </div>
                <div className={'fright'}></div>
            </div>
        )
    }

}

export default SearchResultsPage;

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Material-UI component not being rendered with react-rails prerender

React - Slow state setting for dynamic rendered semantic UI dropdown component

React component not rendered in loop

React component is not being rendered

React pagination component

Pagination in Material UI in React

React component is getting rendered twice

React component Game not rendered with route

React dynamically rendered component not updating

React component being re rendered

React Router | Component not getting rendered

Child Component not rendered in react js

Child Component Not Being Rendered - React

My childrens components are not rendered inside my Drawer component - Material UI, React

How to make a react component that can be rendered with no data and later rendered with data?

React - Redux State update but not rendered in the component

React useState hook - component is rendered twice

Why the React List component gets rendered twice?

React-Router: Component is not rendered but URL changes

react router changes the URL, but the component is not rendered

React component rendered twice and useEffect not triggered

How to access elements rendered in another React component?

React Router: access history in rendered Route component

Component is not Getting Rendered - Dynamic Routing React

React Component with Dynamic Tag Name Not Rendered

React proptypes warning before component is rendered?

Incorrect casing error with dynamically rendered component in React

React Native different categories rendered to header component

Formik component not being rendered with react-tabs