App.jsx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 |
import React, { useState, useEffect } from 'react'; import InfiniteScroll from 'react-infinite-scroll-component'; import { Card, Container, Row, Col, Button } from 'react-bootstrap'; import "bootstrap/dist/css/bootstrap.min.css" // Dummy API request function for demonstration const fetchData = (page, limit) => { return new Promise((resolve) => { setTimeout(() => { const items = []; for (let i = 0; i < limit; i++) { items.push({ id: page * limit + i, name: `Item ${page * limit + i}` }); } resolve(items); }, 1000); }); }; const InfiniteScrollComponent = () => { const [items, setItems] = useState([]); const [hasMore, setHasMore] = useState(true); const [page, setPage] = useState(1); useEffect(() => { // Fetch initial data loadData(page); }, []); const loadData = async (page) => { const newItems = await fetchData(page, 10); setItems((prevItems) => [...prevItems, ...newItems]); if (newItems.length < 10) { setHasMore(false); // No more data available } }; return ( <Container className="mt-4"> <h2>Infinite Scrolling with React-Bootstrap</h2> <InfiniteScroll dataLength={items.length} // Length of the data next={() => { setPage((prevPage) => prevPage + 1); // Load next page loadData(page + 1); }} hasMore={hasMore} loader={<h4>Loading...</h4>} endMessage={<p>No more data</p>} > <Row> {items.map((item) => ( <Col sm={4} key={item.id} className="mb-3"> <Card> <Card.Body> <Card.Title>{item.name}</Card.Title> <Card.Text> Lorem ipsum dolor sit amet, consectetur adipiscing elit. </Card.Text> <Button variant="primary">Details</Button> </Card.Body> </Card> </Col> ))} </Row> </InfiniteScroll> </Container> ); }; export default InfiniteScrollComponent; |