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:
Modify API Routes:
php// routes/api.php
Route::get('/items', 'ItemController@index');
Controller Logic:
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);
}
Install Axios:
bashnpm install axios
Create a React Component:
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.
Lazy Loading (Optional):
react-infinite-scroll-component
.bashnpm 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>
);
Styling and UI Improvements:
Testing:
Remember to adjust the code according to your specific project structure and requirements.