Certainly! To implement a paging component similar to e-commerce websites like AliExpress, we need to assume dynamic data handling where we don't know the total number of pages upfront. Instead, you might fetch data from an API that gives you more data as you navigate. This approach will be similar to infinite scrolling but with paging controls.
I’ll provide a TypeScript version with a simulated asynchronous data fetch to demonstrate the idea:
First, install TypeScript and necessary packages if you haven't already:
npm install --save-dev typescript @types/react @types/node
Create a tsconfig.json file to set up your TypeScript configuration if it's not already present:
{
"compilerOptions": {
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
"exclude": ["node_modules"]
}
Then create the necessary components in TypeScript:
Paging Component
// components/Paging.tsx
import React from 'react';
import { useRouter } from 'next/router';
interface PagingProps {
currentPage: number;
onPageChange: (newPage: number) => void;
hasMore: boolean;
}
const Paging: React.FC<PagingProps> = ({ currentPage, onPageChange, hasMore }) => {
return (
<div className="paging">
<button onClick={() => onPageChange(currentPage - 1)} disabled={currentPage === 1}>
Previous
</button>
<span>Page {currentPage}</span>
<button onClick={() => onPageChange(currentPage + 1)} disabled={!hasMore}>
Next
</button>
<style jsx>{`
.paging {
display: flex;
justify-content: center;
align-items: center;
margin: 20px 0;
}
button {
border: none;
background-color: lightgray;
margin: 0 5px;
padding: 5px 10px;
cursor: pointer;
}
button:disabled {
cursor: not-allowed;
background-color: darkgray;
}
span {
margin: 0 10px;
}
`}</style>
</div>
);
};
export default Paging;
Index Page with Mock Data Fetch
// pages/index.tsx
import React, { useState, useEffect } from 'react';
import { useRouter } from 'next/router';
import Paging from '../components/Paging';
// Mock fetch function
const fetchItems = async (page: number) => {
return new Promise<{ items: string[], hasMore: boolean }>((resolve) => {
const ITEMS_PER_PAGE = 10;
const totalItems = 100; // Simulating 100 items, for example
const start = (page - 1) * ITEMS_PER_PAGE;
const end = start + ITEMS_PER_PAGE;
const hasMore = end < totalItems;
const items = Array.from({ length: Math.min(ITEMS_PER_PAGE, totalItems - start) }, (_, i) => `Item #${start + i + 1}`);
setTimeout(() => resolve({ items, hasMore }), 500); // Simulate network delay
});
};
const IndexPage: React.FC = () => {
const router = useRouter();
const [currentPage, setCurrentPage] = useState(1);
const [items, setItems] = useState<string[]>([]);
const [hasMore, setHasMore] = useState(true);
const loadItems = async (page: number) => {
const { items, hasMore } = await fetchItems(page);
setItems(items);
setHasMore(hasMore);
setCurrentPage(page);
};
useEffect(() => {
loadItems(currentPage);
}, [currentPage]);
const handlePageChange = (newPage: number) => {
if (newPage > 0) {
loadItems(newPage);
}
};
return (
<div>
<h1>Paginated Items</h1>
<ul>
{items.map(item => (
<li key={item}>{item}</li>
))}
</ul>
<Paging currentPage={currentPage} onPageChange={handlePageChange} hasMore={hasMore} />
</div>
);
};
export default IndexPage;
Explanation:
- Paging Component: This component renders navigation buttons. It receives
currentPage, onPageChange, and hasMore props to manage button states.
- Mock Fetch: The
fetchItems function simulates an API call to return a page of items and a hasMore boolean to indicate if there are more data pages available.
- Index Page: Manages current items and pages using local state, simulates fetching data upon page change, and updates the component with the fetched result.
In a real-world application, replace fetchItems with API calls to a backend service that supports pagination. Adjust the component as needed based on your exact data structure and API requirements.