How to implement data pagination and lazy loading in React with Laravel backend



Image not found!!

Implementing data pagination and lazy loading in a React application with a Laravel backend involves several steps. The general idea is to request and display a subset of data at a time, improving the user experience by reducing the initial load time. Here's a step-by-step guide:

Laravel Backend:

  1. Modify API Routes:

    • Create an API route for fetching paginated data.
    php
    // routes/api.php Route::get('/items', 'ItemController@index');
  2. Controller Logic:

    • Implement the logic in the controller to handle paginated data retrieval.
    php
    // app/Http/Controllers/ItemController.php use App\Models\Item; public function index(Request $request) { $perPage = $request->input('per_page', 10); $items = Item::paginate($perPage); return response()->json($items); }

React Frontend:

  1. Install Axios:

    • Axios is a popular HTTP client for making API requests. Install it if you haven't already.
    bash
    npm install axios
  2. Create a React Component:

    • Create a React component to fetch and display paginated data.
    jsx
    // src/components/ItemsList.js import React, { useState, useEffect } from 'react'; import axios from 'axios'; const ItemsList = () => { const [items, setItems] = useState([]); const [page, setPage] = useState(1); useEffect(() => { // Fetch data from the backend axios.get(`http://your-api-url/items?page=${page}`) .then(response => setItems(response.data.data)) .catch(error => console.error(error)); }, [page]); return ( <div> {/* Render items here */} {items.map(item => ( <div key={item.id}>{item.name}</div> ))} {/* Pagination controls */} <button onClick={() => setPage(page - 1)} disabled={page === 1}>Previous</button> <button onClick={() => setPage(page + 1)}>Next</button> </div> ); }; export default ItemsList;

    Adjust the API URL accordingly based on your Laravel backend setup.

  3. Lazy Loading (Optional):

    • If you want to implement lazy loading (load more items as the user scrolls), you can use libraries like react-infinite-scroll-component.
    bash
    npm install react-infinite-scroll-component
    jsx
    // src/components/ItemsList.js import InfiniteScroll from 'react-infinite-scroll-component'; // Wrap the items rendering with InfiniteScroll component return ( <InfiniteScroll dataLength={items.length} next={() => setPage(page + 1)} hasMore={true} // Check if there are more items to load loader={<h4>Loading...</h4>} > {/* Render items here */} {items.map(item => ( <div key={item.id}>{item.name}</div> ))} </InfiniteScroll> );
  4. Styling and UI Improvements:

    • Style your component, add loading spinners, and handle UI based on your application requirements.
  5. Testing:

    • Test your React component to ensure that pagination and lazy loading work as expected.

Remember to adjust the code according to your specific project structure and requirements.