Search code examples
javascriptreactjspaginationantd

How to list 4 products on every page using ant design Pagination component in react js?


How to list 4 products on every page using ant design Pagination component in react js?

Here are the details: I actually want to display 4 products on every page using ant design pagination. I have code that works correctly. (i.e in the beginning 4 products display on every page). But there is one issue. I have search and filtering as well in that component.

When I search a product, if I found more than 4 products, that display on a single page but I want that after search if there are more than 4 products found then 4 products shown on every page as well. Please help me. I have tried my best but not get correct solution.

Here is my data.js file:

export const data = [
    {
      logo: "",
      link: "Men's Rogaine 5% Minoxidil Foam For Hair Loss And Hair Regrowth",
      id: "681c6e998744",
      category: "Biotech",
      manufacturer: "Johanson & Johanson (PVT) LTD",
      active: "Minoxidil:5%",
      drug_strength: "5%",
      drug_form: "Injection",
      pack_size: "1 vial",
    },
    {
      logo:"",
  
      link: "Men's Rogaine 5% Minoxidil Foam For Hair Loss And Hair Regrowth",
      id: "681cc76998755",
      category: " Health",
      manufacturer: "Talha",
      active: "Minoxidil:10%",
      drug_strength: "5%",
      drug_form: "Injection",
      pack_size: "1 vial",
    },
  
    {
      logo:"",
  
      link: "Men's Rogaine 5% Minoxidil Foam For Hair Loss And Hair Regrowth",
      id: "681cc76998766",
      category: " Health",
      manufacturer: "David",
      active: "Minoxidil:15%",
      drug_strength: "5%",
      drug_form: "Injection",
      pack_size: "1 vial",
    },
  
    {
      logo:"",
  
      link: "Men's Rogaine 5% Minoxidil Foam For Hair Loss And Hair Regrowth",
      id: "681cc76998777",
      category: " Health",
      manufacturer: "saad",
      active: "Minoxidil:125%",
      drug_strength: "5%",
      drug_form: "Injection",
      pack_size: "1 vial",
    },
  
    {
      logo:"",
  
      link: "Fashion",
      id: "681cc76998788",
      category: "Health",
      manufacturer: "Fahad",
      active: "Minoxidil:95%",
      drug_strength: "5%",
      drug_form: "Injection",
      pack_size: "1 vial",
    },
  
    {
      logo:"",
  
      link: "Men's Rogaine 5% Minoxidil Foam For Hair Loss And Hair Regrowth",
      id: "681cc76998799",
      category: "ABC",
      manufacturer: "ABC",
      active: "Minoxidil:25%",
      drug_strength: "5%",
      drug_form: "Injection",
      pack_size: "1 vial",
    },
  
    {
      logo:"",
  
      link: "Men's Rogaine 5% Minoxidil Foam For Hair Loss And Hair Regrowth",
      id: "68",
      category: "electronic",
      manufacturer: "Awais",
      active: "Minoxidil:5%",
      drug_strength: "5%",
      drug_form: "Injection",
      pack_size: "1 vial",
    },
  
    {
      logo:"",
  
      link: "Men's Rogaine 5% Minoxidil Foam For Hair Loss And Hair Regrowth",
      id: "681c",
      category: " Electric",
      manufacturer: "musa",
      active: "Minoxidil:5%",
      drug_strength: "5%",
      drug_form: "Injection",
      pack_size: "1 vial",
    },
  
    {
      logo:"",
      link: "GNC",
      id: "681cc76e992222",
      category: " GNC supplements, Proteins and Supplements",
      manufacturer: "Johanson & Johanson (PVT) LTD",
      active: "Minoxidil:5%",
      drug_strength: "5%",
      drug_form: "Injection",
      pack_size: "1 vial",
    },
  
    {
      logo:"",
      link: "XYZ",
      id: "681cc76e9983333",
      category: " XYZ",
      manufacturer: "XYZ",
      active: "Minoxidil:5%",
      drug_strength: "5%",
      drug_form: "Injection",
      pack_size: "1 vial",
    },
  
    {
      link: "EFG",
      id: "681cc76e99744444",
      category: "EFG",
      manufacturer: "",
      active: "Minoxidil:5%",
      drug_strength: "5%",
      drug_form: "Injection",
      pack_size: "1 vial",
    },
    {
      logo:"",
      link: "HIJ",
      id: "1",
      category: "HIJ",
      manufacturer: "",
      active: "Minoxidil:5%",
      drug_strength: "5%",
      drug_form: "Injection",
      pack_size: "1 vial",
    },
    {
      logo:"",
      link: "KLM",
      id: "12",
      category: "KLM",
      manufacturer: "",
      active: "Minoxidil:5%",
      drug_strength: "5%",
      drug_form: "Injection",
      pack_size: "1 vial",
    },
    {
      logo:"",
      link: "NOP",
      id: "123",
      category: "NOP",
      manufacturer: "",
      active: "Minoxidil:5%",
      drug_strength: "5%",
      drug_form: "Injection",
      pack_size: "1 vial",
    },
    {
      logo:"",
      link: "QRS",
      id: "1234",
      category: "QRS",
      manufacturer: "",
      active: "Minoxidil:5%",
      drug_strength: "5%",
      drug_form: "Injection",
      pack_size: "1 vial",
    },
    {
      logo:"",
      link: "TUV",
      id: "123456",
      category: "TUV",
      manufacturer: "",
      active: "Minoxidil:5%",
      drug_strength: "5%",
      drug_form: "Injection",
      pack_size: "1 vial",
    },
  ];
  

Here is my Searching.js component code:

import React, { useState } from "react";
import "./searching.css";
import { data } from "./data";
import { FilterOutlined } from "@ant-design/icons";
import {
  Typography,
  Space,
  Card,
  Button,
  Tree,
  Input,
  Pagination,
  Empty,
  Modal,
} from "antd";

const Searching = () => {
  const { Text, Title, Link } = Typography;
  const { Search } = Input;
  
   // dynamic data
  const [maindata, setMainData] = useState(data?.slice(0, 4));

  // search filteration states
  const [search, setSearch] = useState("");
  const exculdeData = [
    "id",
    "logo",
    "link",
    "category",
    "drug_strength",
    "drug_form",
    "pack_size",
  ];

  // pagination states
  const [number, setNumber] = useState(1);
  const [postsPerPage] = useState(4);
//   handle Pagination
  const handlePage = (pageNumber) => {
    console.log(pageNumber);
    setNumber(pageNumber);

    const indexOfLastPost = pageNumber * postsPerPage;
    const indexOfFirstPost = indexOfLastPost - postsPerPage;
    const currentPosts = data?.slice(indexOfFirstPost, indexOfLastPost);
    setMainData(currentPosts);
  };
//   handle search change
  const handleChange = (value) => {
    setSearch(value);
  };
  
   //   click on search button to trigger it
  const onSearch = (value) => {
    const lowerCaseValue = value.toLowerCase().trim();
    if (!lowerCaseValue) {
      setMainData(data);
    } else {
      const filterSearch = data.filter((item) => {
        // console.log(Object.keys(item));
        return Object.keys(item).some((key) => {
          // console.log(key);
          return exculdeData.includes(key)
            ? false
            : item[key].toString().toLowerCase().includes(lowerCaseValue);
        });
      });
      // consoleFun(filterSearch)
      setMainData(filterSearch);
    }
  };
  
   return (
    <div>
      <div style={{ width: "90%" }}>
        <div className="banner">
          <Text>
            <Title level={3} className="search_title">
              Search Products
            </Title>
          </Text>
          <Text>
            <Title level={5}>
              Find numerous unregistered products that can fulfill you need
            </Title>
          </Text>
        </div>
        <div className="main_container">
          {/* for search */}
         

          <div>
            <Search
              enterButton="Search"
              size="large"
              placeholder="Search Product"
              className="search_bar"
              onSearch={onSearch}
              onChange={(e) => handleChange(e.target.value)}
            />
          </div>
         
        </div>
        {/* for showing result */}
        <div className="showing_result">
          <div className="filter_search">
            <Text>Showing results for {`"${search} "`}</Text>
          </div>{" "}
          <div className="filter_result">
            <Text>
              showing {number}-{postsPerPage} of {data?.length} results
            </Text>
          </div>
        </div>

        {/* for showing cards data */}
        {maindata.length ? (
          maindata.map((item) => {
            const {
              logo,
              link,
              id,
              category,
              manufacturer,
              active,
              drug_strength,
              drug_form,
              pack_size,
            } = item;
            return (
              <div key={id} className="card">
                <Card>
                  <div className="card_container">
                    <div>
                      <img
                        src="https://picsum.photos/200/300"
                        alt="product image"
                        className="cards_img"
                      />
                      
                    </div>
                    <Space direction="vertical" className="card_data">
                      <img src="" alt="Logo" />
                      <Text>
                        <Link>
                          <strong className="card_link">{link}</strong>
                        </Link>
                      </Text>
                      <Text type="secondary">
                        Product ID: <Text>{id}</Text>
                      </Text>

                      <Text type="secondary">
                        Category:
                        <Text className="blue_text">{category}</Text>
                      </Text>

                      <Text type="secondary">
                        Manufecture:{" "}
                        <Text className="blue_text">{manufacturer}</Text>
                      </Text>

                      <Text type="secondary">
                        Active Pharmaceutical Ingredients:{" "}
                        <Text className="blue_text">{active}</Text>
                      </Text>

                      <Text type="secondary">
                        Drug Strength: <Text>{drug_strength}</Text>
                      </Text>

                      <Text type="secondary">
                        Drug Form: <Text>{drug_form}</Text>
                      </Text>

                      <Text type="secondary">
                        Pack Size: <Text>{pack_size}</Text>
                      </Text>
                      <Space className="buttons">
                        <Space>
                          <Button type="primary">View Details</Button>
                          <Button style={{ background: "green" }}>
                            Send RFI
                          </Button>
                        </Space>
                      </Space>
                    </Space>
                  </div>
                </Card>
              </div>
            );
          })
        ) : (
          <div className="empty_container">
            <div>
              <Empty description={false} className="empty_data">
                No Product Found
              </Empty>
            </div>
          </div>
        )}
        <div className="pagination">
          {maindata?.length == 0 ? null : search?.length ? (
            <Space>
              <Pagination
                defaultCurrent={number}
                total={maindata?.length}
                defaultPageSize={postsPerPage}
                onChange={handlePage}
              />
            </Space>
          ) : (
            <Space>
              <Pagination
                defaultCurrent={number}
                total={data?.length}
                defaultPageSize={postsPerPage}
                onChange={handlePage}
              />
            </Space>
          )}
        </div>
      </div>
    </div>
  );
};

export default Searching;


Solution

  • I just made few changes in your code & now it's working.

    1. I create a copy of main data & store it in a state mainData.
    2. In onSearch function, i reset the page to number 1 to always show the first 4 records of mainData if available
    3. Check the following code how i get the list to show cards.
    let newData = maindata.slice((number - 1) * postsPerPage, postsPerPage * number);
    
    1. Removed one pagination component. (You were using two Antd Pagination Component)
    import { useState } from 'react';
    import { Typography, Space, Card, Button, Input, Pagination, Empty } from 'antd';
    
    const { Text, Title, Link } = Typography;
    const { Search } = Input;
    const exculdeData = ['id', 'logo', 'link', 'category', 'drug_strength', 'drug_form', 'pack_size'];
    const postsPerPage = 4;
    
    const Container = () => {
        // dynamic data
        const [maindata, setMainData] = useState(data || []);
        // search filteration states
        const [search, setSearch] = useState('');
        // pagination states
        const [number, setNumber] = useState(1);
    
        //   handle Pagination
        const handlePage = (pageNumber) => setNumber(pageNumber);
    
        //   handle search change
        const handleChange = (value) => setSearch(value);
    
        //   click on search button to trigger it
        const onSearch = (value) => {
            const lowerCaseValue = value.toLowerCase().trim();
            if (!lowerCaseValue) {
                setMainData(data);
            } else {
                const filterSearch = data.filter((item) => {
                    return Object.keys(item).some((key) => {
                        return exculdeData.includes(key) ? false : item[key].toString().toLowerCase().includes(lowerCaseValue);
                    });
                });
                setNumber(1);
                setMainData(filterSearch);
            }
        };
    
        let newData = maindata.slice((number - 1) * postsPerPage, postsPerPage * number);
    
        return (
            <div>
                <div style={{ width: '90%' }}>
                    <div className='banner'>
                        <Text>
                            <Title level={3} className='search_title'>
                                Search Products
                            </Title>
                        </Text>
                        <Text>
                            <Title level={5}>Find numerous unregistered products that can fulfill you need</Title>
                        </Text>
                    </div>
                    <div className='main_container'>
                        <div>
                            <Search
                                enterButton='Search'
                                size='large'
                                placeholder='Search Product'
                                className='search_bar'
                                onSearch={onSearch}
                                onChange={(e) => handleChange(e.target.value)}
                            />
                        </div>
                    </div>
                    {/* for showing result */}
                    <div className='showing_result'>
                        <div className='filter_search'>
                            <Text>Showing results for {`"${search} "`}</Text>
                        </div>{' '}
                        <div className='filter_result'>
                            <Text>
                                showing {maindata.length === 0 ? 0 : number}-{maindata.length < postsPerPage ? maindata.length : postsPerPage} of{' '}
                                {maindata.length} results
                            </Text>
                        </div>
                    </div>
    
                    {/* for showing cards data */}
                    {newData.length ? (
                        newData.map((item) => {
                            const { logo, link, id, category, manufacturer, active, drug_strength, drug_form, pack_size } = item;
                            return (
                                <div key={id} className='card'>
                                    <Card>
                                        <div className='card_container d-flex'>
                                            <div>
                                                <img src='https://picsum.photos/200/300' alt='product image' className='cards_img' />
                                            </div>
                                            <Space direction='vertical' className='card_data'>
                                                <img src='' alt='Logo' />
                                                <Text>
                                                    <Link>
                                                        <strong className='card_link'>{link}</strong>
                                                    </Link>
                                                </Text>
                                                <Text type='secondary'>
                                                    Product ID: <Text>{id}</Text>
                                                </Text>
    
                                                <Text type='secondary'>
                                                    Category:
                                                    <Text className='blue_text'>{category}</Text>
                                                </Text>
    
                                                <Text type='secondary'>
                                                    Manufecture: <Text className='blue_text'>{manufacturer}</Text>
                                                </Text>
    
                                                <Text type='secondary'>
                                                    Active Pharmaceutical Ingredients: <Text className='blue_text'>{active}</Text>
                                                </Text>
    
                                                <Text type='secondary'>
                                                    Drug Strength: <Text>{drug_strength}</Text>
                                                </Text>
    
                                                <Text type='secondary'>
                                                    Drug Form: <Text>{drug_form}</Text>
                                                </Text>
    
                                                <Text type='secondary'>
                                                    Pack Size: <Text>{pack_size}</Text>
                                                </Text>
                                                <Space className='buttons'>
                                                    <Space>
                                                        <Button type='primary'>View Details</Button>
                                                        <Button style={{ background: 'green' }}>Send RFI</Button>
                                                    </Space>
                                                </Space>
                                            </Space>
                                        </div>
                                    </Card>
                                </div>
                            );
                        })
                    ) : (
                        <div className='empty_container'>
                            <div>
                                <Empty description={false} className='empty_data'>
                                    No Product Found
                                </Empty>
                            </div>
                        </div>
                    )}
                    <div className='pagination'>
                        {!!maindata.length && (
                            <Space>
                                <Pagination
                                    defaultCurrent={number}
                                    pageSize={postsPerPage}
                                    total={maindata.length}
                                    onChange={handlePage}
                                />
                            </Space>
                        )}
                    </div>
                </div>
            </div>
        );
    };
    
    export default Container;