skip to Main Content

I have an items api which is working fine and I added the active className on Pagination.Item but its not working. I’m not sure if I missed something else to make it work.

See docs for pagination react-bootstrap.github.io

Below is my code and also here is the sandbox code https://codesandbox.io/.

Movielist.js

import { React, useState, useEffect } from "react";
import { Col, Card, Row, Pagination } from "react-bootstrap";
import MovieListPagination from "./MovieListPagination";

const MovieList = () => {
  const [error, setError] = useState(null);
  const [isLoaded, setIsLoaded] = useState(false);
  const [items, setItems] = useState([]);
  // Default current pages and posts
  const [currentPage, setCurrentPage] = useState(1);
  const [postsPerPage] = useState(4);
  // Get current posts
  const indexOfLastPost = currentPage * postsPerPage;
  const indexOfFirstPost = indexOfLastPost - postsPerPage;
  const currentPosts = items.slice(indexOfFirstPost, indexOfLastPost);
  // Change page
  const paginate = (pageNumber) => setCurrentPage(pageNumber);

  useEffect(() => {
    fetch("https://jsonplaceholder.typicode.com/posts")
      .then((res) => res.json())
      .then(
        (result) => {
          setIsLoaded(true);
          setItems(result);
          //console.log(result.results);
        },
        (error) => {
          setIsLoaded(true);
          setError(error);
        }
      );
  }, []);

  if (error) {
    return <div className="p-3">Error: {error.message}</div>;
  } else if (!isLoaded) {
    return <div className="p-3">Loading...</div>;
  } else {
    return (
      <>
        <Row className="justify-content-center">
          {currentPosts.map((item) => (
            <Col sm={6} lg={4} xl={3} className="py-3" key={item.id}>
              <Card bg="dark" text="light" className="text-center h-100">
                <Card.Body>
                  <Card.Title>{item.title}</Card.Title>
                  <Card.Text>{item.body}</Card.Text>
                </Card.Body>
              </Card>
            </Col>
          ))}
          <Pagination className="justify-content-center">
            <MovieListPagination
              postsPerPage={postsPerPage}
              totalPosts={items.length}
              paginate={paginate}
            />
          </Pagination>
        </Row>
      </>
    );
  }
};

export default MovieList;

MovielistPagination.js

import { React } from "react";
import { Pagination } from "react-bootstrap";

const MovieListPagination = ({
  currentPage,
  postsPerPage,
  totalPosts,
  paginate
}) => {
  const pageNumbers = [];
  for (let i = 1; i <= Math.ceil(totalPosts / postsPerPage); i++) {
    pageNumbers.push(i);
  }
  return (
    <>
      <Pagination.First />
      <Pagination.Prev />
      {pageNumbers.map((number) => (
        <Pagination.Item
          key={number}
          className={`${currentPage === number ? "active" : ""}`}
          onClick={() => {
            paginate(number);
          }}
        >
          {number}
        </Pagination.Item>
      ))}
      <Pagination.Next />
      <Pagination.Last />
      {/* {item.alt_description ? item.alt_description : item.user.name + ' Collection'} */}
    </>
  );
};

export default MovieListPagination;

3

Answers


  1. Pass currentPage to the Component

    <MovieListPagination
      currentPage={currentPage}     // You missed this line
      postsPerPage={postsPerPage}
      totalPosts={items.length}
      paginate={paginate}
    />
    
    Login or Signup to reply.
  2. In this component, you take the "currentPage" prop, but don’t pass that prop when using the component. At the time of using the component, you must pass props like this:

    `<MovieListPagination
         currentPage={currentPage}     <<
         postsPerPage={postsPerPage}
         totalPosts={items.length}
         paginate={paginate} 
      />`
    

    Also, even if you pass this prop, you won’t see the class because you’re using validation incorrectly. I’m assuming you want to use type checking. If you want to use type checking, you must typecheck

    className={“${typeof currentPage === "number" ? "active" : ""}`}

    Login or Signup to reply.
  3. you forgot to pass currentPage prop to MovieListPagination component

        <MovieListPagination
      currentPage={currentPage}     // add this line
      postsPerPage={postsPerPage}
      totalPosts={items.length}
      paginate={paginate}
    />
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search