vivek kn
vivek kn

Reputation: 275

react js i am trying to make a pagination

i am trying to make a pagination and filter based on experience i want max only 10 items in a page i dont know how to get stated i have all the days dispayed and all day is now dispalyed in single page i want only 10 items in 1 page and next 10 items in next page

import { useState, useEffect } from "react";
import { Link } from "react-router-dom";
import DocPic from "../img/doctor.png";
import InnerDetail from "./innerto_detail";
import axios from "axios";
export default function InnerSpecialities() {
 const [hasId, setHasId] = useState(false);
 const [detail, setDetail] = useState(false);
 const [data, setdata] = useState([]);
 const inipath = window.location.pathname;
 const id_path = inipath.split("/cdoctor/details");
 const path = inipath.split("/cdoctor/");
 useEffect(() => {
   const pathname = window.location.pathname;
   const doctorId = pathname.split("/")[2];
   console.log("this is the ", doctorId);
   console.log(id_path);
   const substring = "detiled";
   console.log(inipath.includes(substring));
   if (inipath.includes(substring) === true) {
     setDetail(true);
   }
   const config = {
     headers: {
       Authorization: `token ` + localStorage.getItem("token"),
     },
   };

   axios
     .get(
       "filter/?speciality=" +
         path[1],
       config
     )
     .then((res) => {
  
       var somevariable = res;
       setdata((data) => {
         return [...data, somevariable];
       });

       setdata(res.data);
      
     });
 }, []);

 function OpenInner() {
   setDetail(true);
 }

 return (
   <>
     {detail ? (
       <InnerDetail />
     ) : (
       <div>

         <div>
           <div className="list-container" style={styles.options}>
          

             <div style={styles.inneropt}>
               <i style={styles.rotate} class="fa fa-exchange"></i>Sort By:
               <select style={styles.sel}>
                 <option> Availability</option>
                 <option> Nearby</option>
                 <option> Price- Low to high</option>
                 <option> Price- High to low</option>
               </select>{" "}
             </div>
             <div style={styles.inneropt}>
               Gender:
               <select style={styles.sel}>
                 <option> Male</option>
                 <option> Female</option>
               </select>{" "}
             </div>
             <div style={styles.inneropt}>
               Experience:
               <select style={styles.sel}>
                 <option> 0-5</option>
                 <option> 5-10</option>
                 <option> 10-15</option>
                 <option> 15+ </option>
               </select>{" "}
             </div>
             <div className="splang" style={styles.inneropt}>
               Language:
               <select style={styles.sel}>
                 <option> English</option>
                 <option> Malayaliam</option>
                 <option> Tamil</option>
                 <option> Kannada</option>
               </select>{" "}
             </div>
           </div>

           <div style={styles.container}>
             {data.map((personData, key) => {
               return (
                 <div style={styles.fbox}>
                   <div style={styles.fitem}>
                     <left>
                       <img src={DocPic} alt="" />
                       <br />
                       <i className="fa fa-video-camera"></i>
                       <br />
                       <small>Online</small>
                     </left>
                     <right style={{ textAlign: "left", marginLeft: "6px" }}>
                       <strong>
                         Dr {personData.firstname}&nbsp;
                         {personData.lastname}
                       </strong>
                       <br />
                       <small>
                         {" "}
                         {personData.speciality} |{personData.experience}
                         <small> years Exp.</small>
                       </small>
                       <br />
                       <strong>You Pay</strong>
                       <br />
                       <strong>$600</strong>
                       <br />
                       <small>
                         {personData.qualification}
                         {personData.location}
                       </small>
                     </right>
                   </div>
                   <Link
                     to={{
                       pathname: "/doctor/detiled/" + personData.id,
                       state: { id: personData.id, data: personData },
                     }}
                     onClick={OpenInner}
                   >
                     <button style={styles.book}>Book Appointments</button>
                   </Link>
                 </div>
               );
             })}
           
           </div>

         

           <div style={styles.pagination} className="pagination">
             <div className="pager" style={{ margin: "auto", width: "30rem" }}>
               <Link to="">
                 {" "}
                 <i className="fa fa-angle-left"></i>{" "}
               </Link>
               <Link to="">1</Link>
               <Link to="">2</Link>
               <Link to="">3</Link>
               <Link to="">4</Link>
               <Link to="">5</Link>
               <Link to="">6</Link>
               <Link to="">7</Link>
               <Link to="">
                 {" "}
                 <i className="fa fa-angle-right"></i>{" "}
               </Link>
             </div>

             
           </div>
         </div>
       </div>
     )}
   </>
 );
}

i am trying to make a pagination and filter based on experience i want max only 10 items in a page i dont know how to get stated i have all the days dispayed and all day is now dispalyed in single page i want only 10 items in 1 page and next 10 items in next page

Upvotes: 0

Views: 419

Answers (2)

dee
dee

Reputation: 2434

Have state variables for loading and the page count,

const [data, setData] = useState([]);
const [loading, setLoading] = useState(false);
const [currentPage, setCurrentPage] = useState(1); 
const [dataPerPage, setDataPerPage] = useState(10); // 10 items needed per page

Your API call response should set the loading status after the setData()

useEffect(()=>{
 function getData(){

       setLoading(true);  // until the response is available, user will see loader
        axios
             .get(
               "filter/?speciality=" +
                 path[1],
               config
             )
             .then((res) => {
          
               var somevariable = res;
               setdata(res.data);
               setLoading(false);
       
             }).catch(....)
     }
       
getData();

},[])
 

Here is the pagination logic,

const indexOfLastdata = currentPage * dataPerPage; // 1 * 10   
const indexOfFirstData = indexOfLastdata - dataPerPage; 
const currentData = posts.slice(indexOfFirstData, indexOfLastData); 

First page index will be index of last data minus the number of data you want to allow per page, when this is zero, its first page, if its 10 then its second page and so on. You'll control this through the current page number on click of next/number of the page.

Example pagination component below will take total data available, the posts allowed per page and paginate function as props.

const Pagination = ({dataPerPage, totalData, paginate}) => {
    
        const pageNumbers = [];
    
        for(let i=1; i<= Math.ceil(totaldata/dataPerPage); i++){
            pageNumbers.push(i);
        }
    
        return (
          <nav>
              <ul className="ur style class for nav">
                  {pageNumbers.map(number=>{
                      return <li key={number}>
                         <a onClick={ () => paginate(number) } className={currentPage===number ? "active": ""}>
                             {number}
                         </a>
                      </li>
                  })}
              </ul>
          </nav>
        );
    };

  

In your component,

return (
            <div>
                <Data data={currentData} loading={loading}/>
                <Pagination dataPerPage={dataPerPage} totalData={data.length} paginate={handlePaginate}/>
            </div>
    
        )
    

I have created a codesandbox with a working example for you here.

https://codesandbox.io/s/mutable-water-msoy9

Upvotes: 1

user2063635
user2063635

Reputation: 214

You need to set the pageCount and pageSize variables. Page size would be 10 in your case. Based on the current current page index, you need to extract that part of your data array and render on that page.

Upvotes: 1

Related Questions