javascript - Pagination and Card Components with Ant Design (antd)?

Javascript - Pagination and Card Components with Ant Design (antd)?

Ant Design (AntD) provides a comprehensive suite of UI components, including pagination and card components, which can be used together to create a paginated list of cards. Below, We'll guide you through creating a paginated card list using AntD's Pagination and Card components.

Step-by-Step Guide

  1. Set Up Your React Project Ensure you have a React project set up. If not, you can create one using Create React App:

    npx create-react-app my-antd-app cd my-antd-app 
  2. Install Ant Design Install Ant Design and its dependencies:

    npm install antd 
  3. Create the Card and Pagination Components Create a React component that uses AntD's Card and Pagination components.

  4. Implement the Pagination Logic Implement the logic to handle pagination and display a subset of cards based on the current page.

Example Code

import React, { useState } from 'react'; import { Card, Pagination, Row, Col } from 'antd'; import 'antd/dist/antd.css'; const { Meta } = Card; const data = Array.from({ length: 50 }, (_, i) => ({ title: `Card Title ${i + 1}`, description: `Card Description ${i + 1}`, image: 'https://via.placeholder.com/150', })); const PAGE_SIZE = 8; const PaginatedCardList = () => { const [currentPage, setCurrentPage] = useState(1); const handlePageChange = (page) => { setCurrentPage(page); }; const startIndex = (currentPage - 1) * PAGE_SIZE; const endIndex = startIndex + PAGE_SIZE; const currentPageData = data.slice(startIndex, endIndex); return ( <div> <Row gutter={[16, 16]}> {currentPageData.map((item, index) => ( <Col key={index} xs={24} sm={12} md={8} lg={6}> <Card hoverable cover={<img alt={item.title} src={item.image} />} > <Meta title={item.title} description={item.description} /> </Card> </Col> ))} </Row> <Pagination current={currentPage} pageSize={PAGE_SIZE} total={data.length} onChange={handlePageChange} style={{ marginTop: '16px', textAlign: 'center' }} /> </div> ); }; const App = () => { return ( <div style={{ padding: '24px' }}> <h1>Paginated Card List</h1> <PaginatedCardList /> </div> ); }; export default App; 

Explanation

  1. Import Dependencies:

    • Import React and useState from 'react'.
    • Import Card, Pagination, Row, and Col from 'antd'.
    • Import the AntD stylesheet.
  2. Data Source:

    • Create a sample data array containing objects with title, description, and image properties.
  3. Page Size Constant:

    • Define a constant PAGE_SIZE to control how many cards are displayed per page.
  4. PaginatedCardList Component:

    • Maintain the current page state using the useState hook.
    • Define the handlePageChange function to update the current page.
    • Calculate the start and end indices of the data slice based on the current page.
    • Extract the subset of data for the current page.
    • Render the cards using AntD's Card component within a Row and Col layout.
    • Render the Pagination component and handle the onChange event to update the current page.
  5. App Component:

    • Render the PaginatedCardList component within a div with padding.

Running the Project

  1. Start the Development Server: Start your React development server:

    npm start 
  2. View the Application: Open your web browser and navigate to http://localhost:3000 to view the paginated card list.

By following this guide, you can create a paginated card list using Ant Design in a React application. This example demonstrates how to combine AntD components and handle pagination logic to display a subset of cards on each page.

Examples

  1. Ant Design Pagination example

    • Description: This query seeks an example of implementing pagination using Ant Design's Pagination component in a JavaScript application.
    • Code:
      import React, { useState } from 'react'; import { Pagination } from 'antd'; const MyComponent = () => { const [currentPage, setCurrentPage] = useState(1); const pageSize = 10; // Number of items per page const onPageChange = (page) => { setCurrentPage(page); // Optionally, fetch data for the new page here }; return ( <div> {/* Your card components or data display */} {/* Pagination component */} <Pagination current={currentPage} pageSize={pageSize} total={100} onChange={onPageChange} /> </div> ); }; export default MyComponent; 
  2. Ant Design Card component example

    • Description: This query looks for an example of using Ant Design's Card component to display data items in a JavaScript application.
    • Code:
      import React from 'react'; import { Card } from 'antd'; const MyComponent = () => { return ( <Card title="Card Title" style={{ width: 300 }}> <p>Card content</p> </Card> ); }; export default MyComponent; 
  3. Ant Design Pagination and Card integration

    • Description: This query focuses on integrating Ant Design's Pagination and Card components to display paginated data items.
    • Code:
      import React, { useState } from 'react'; import { Pagination, Card } from 'antd'; const MyComponent = () => { const [currentPage, setCurrentPage] = useState(1); const pageSize = 10; // Number of items per page const onPageChange = (page) => { setCurrentPage(page); // Optionally, fetch data for the new page here }; // Dummy data for demonstration const data = Array.from({ length: 10 }).map((_, index) => ({ id: index + 1, title: `Card ${index + 1}`, content: `This is the content of card ${index + 1}`, })); const startIndex = (currentPage - 1) * pageSize; const paginatedData = data.slice(startIndex, startIndex + pageSize); return ( <div> {paginatedData.map(item => ( <Card key={item.id} title={item.title} style={{ width: 300, marginBottom: 16 }}> <p>{item.content}</p> </Card> ))} {/* Pagination component */} <Pagination current={currentPage} pageSize={pageSize} total={data.length} onChange={onPageChange} /> </div> ); }; export default MyComponent; 
  4. Ant Design Pagination with dynamic data

    • Description: This query seeks an example of implementing Ant Design's Pagination component with dynamically loaded data in a JavaScript application.
    • Code:
      import React, { useState, useEffect } from 'react'; import { Pagination, Card } from 'antd'; import axios from 'axios'; // Example of using Axios for API requests const MyComponent = () => { const [data, setData] = useState([]); const [currentPage, setCurrentPage] = useState(1); const pageSize = 10; // Number of items per page useEffect(() => { fetchData(); }, []); const fetchData = async () => { try { // Example API request const response = await axios.get(`https://api.example.com/data?page=${currentPage}&limit=${pageSize}`); setData(response.data); // Assuming response.data is an array of items } catch (error) { console.error('Error fetching data:', error); } }; const onPageChange = (page) => { setCurrentPage(page); fetchData(); }; return ( <div> {data.map(item => ( <Card key={item.id} title={item.title} style={{ width: 300, marginBottom: 16 }}> <p>{item.content}</p> </Card> ))} {/* Pagination component */} <Pagination current={currentPage} pageSize={pageSize} total={100} onChange={onPageChange} /> </div> ); }; export default MyComponent; 
  5. Ant Design Card component with dynamic data

    • Description: This query looks for an example of using Ant Design's Card component to display dynamically loaded data items in a JavaScript application.
    • Code:
      import React, { useState, useEffect } from 'react'; import { Card } from 'antd'; import axios from 'axios'; // Example of using Axios for API requests const MyComponent = () => { const [data, setData] = useState([]); useEffect(() => { fetchData(); }, []); const fetchData = async () => { try { // Example API request const response = await axios.get('https://api.example.com/data'); setData(response.data); // Assuming response.data is an array of items } catch (error) { console.error('Error fetching data:', error); } }; return ( <div> {data.map(item => ( <Card key={item.id} title={item.title} style={{ width: 300, marginBottom: 16 }}> <p>{item.content}</p> </Card> ))} </div> ); }; export default MyComponent; 
  6. Ant Design Pagination with server-side data

    • Description: This query seeks an example of implementing Ant Design's Pagination component with server-side pagination using JavaScript.
    • Code:
      import React, { useState, useEffect } from 'react'; import { Pagination, Card } from 'antd'; import axios from 'axios'; // Example of using Axios for API requests const MyComponent = () => { const [data, setData] = useState([]); const [totalItems, setTotalItems] = useState(0); const [currentPage, setCurrentPage] = useState(1); const pageSize = 10; // Number of items per page useEffect(() => { fetchData(); }, [currentPage]); const fetchData = async () => { try { // Example API request with server-side pagination const response = await axios.get(`https://api.example.com/data?page=${currentPage}&limit=${pageSize}`); setData(response.data.items); // Assuming response.data.items is an array of items setTotalItems(response.data.total); // Assuming response.data.total is the total number of items } catch (error) { console.error('Error fetching data:', error); } }; const onPageChange = (page) => { setCurrentPage(page); }; return ( <div> {data.map(item => ( <Card key={item.id} title={item.title} style={{ width: 300, marginBottom: 16 }}> <p>{item.content}</p> </Card> ))} {/* Pagination component */} <Pagination current={currentPage} pageSize={pageSize} total={totalItems} onChange={onPageChange} /> </div> ); }; export default MyComponent; 
  7. Ant Design Card component with image

    • Description: This query looks for an example of using Ant Design's Card component to display images along with other content in a JavaScript application.
    • Code:
      import React from 'react'; import { Card } from 'antd'; const MyComponent = () => { return ( <Card hoverable style={{ width: 240 }} cover={<img alt="example" src="https://example.com/example.jpg" />} > <Card.Meta title="Card title" description="This is the description" /> </Card> ); }; export default MyComponent; 
  8. Ant Design Pagination with custom page size

    • Description: This query seeks an example of implementing Ant Design's Pagination component with a custom page size in a JavaScript application.
    • Code:
      import React, { useState } from 'react'; import { Pagination, Card } from 'antd'; const MyComponent = () => { const [currentPage, setCurrentPage] = useState(1); const pageSize = 5; // Custom number of items per page const onPageChange = (page) => { setCurrentPage(page); // Optionally, fetch data for the new page here }; return ( <div> {/* Your card components or data display */} <Pagination current={currentPage} pageSize={pageSize} total={100} onChange={onPageChange} /> </div> ); }; export default MyComponent; 

More Tags

single-quotes typescript1.8 utf-16 fill owl-carousel-2 react-native-firebase angular-material-5 dreamweaver typeerror azure-synapse

More Programming Questions

More Weather Calculators

More Everyday Utility Calculators

More Electronics Circuits Calculators

More Investment Calculators