Certainly! Let's create a paginated list of Star Wars characters using React, TypeScript, React Router, and the SWAPI (Star Wars API).
Step 1: Set Up Basic Project Structure
First, make sure you have React and TypeScript set up in your project:
npx create-react-app my-app --template typescript
cd my-app
npm install axios react-router-dom
Step 2: Define Routes and Components
Now we'll create a PeopleList component that fetches data and implements pagination. We'll also set up routing to handle different pages through query parameters.
App.tsx
import React from 'react';
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import PeopleList from './PeopleList';
const App: React.FC = () => {
return (
<Router>
<Routes>
<Route path="/search/:page" element={<PeopleList />} />
<Route path="/search" element={<PeopleList />} />
</Routes>
</Router>
);
};
export default App;
PeopleList.tsx
import React, { useEffect, useState } from 'react';
import { useParams, useNavigate, Link } from 'react-router-dom';
import axios from 'axios';
// Define the type for a person object
interface Person {
name: string;
height: string;
mass: string;
}
interface ApiResponse {
count: number;
next: string | null;
previous: string | null;
results: Person[];
}
const PeopleList: React.FC = () => {
const { page } = useParams<{ page: string }>();
const navigate = useNavigate();
const [people, setPeople] = useState<Person[]>([]);
const [loading, setLoading] = useState<boolean>(false);
const [error, setError] = useState<string | null>(null);
const [currentPage, setCurrentPage] = useState<number>(Number(page) || 1);
const [totalPages, setTotalPages] = useState<number>(1);
useEffect(() => {
setLoading(true);
setError(null);
axios.get<ApiResponse>(`https://swapi.dev/api/people/?page=${currentPage}`)
.then(response => {
setPeople(response.data.results);
setTotalPages(Math.ceil(response.data.count / 10)); // total items divided by items per page
setLoading(false);
})
.catch(error => {
setError('Failed to fetch data.');
setLoading(false);
});
}, [currentPage]);
useEffect(() => {
if (page) {
setCurrentPage(Number(page));
}
}, [page]);
const handlePageChange = (newPage: number) => {
setCurrentPage(newPage);
navigate(`/search/${newPage}`);
};
return (
<div>
<h1>Star Wars Characters</h1>
{loading ? (
<p>Loading...</p>
) : error ? (
<p style={{ color: 'red' }}>{error}</p>
) : (
<ul>
{people.map((person, index) => (
<li key={index}>
{person.name} - Height: {person.height}, Mass: {person.mass}
</li>
))}
</ul>
)}
<Pagination
currentPage={currentPage}
totalPages={totalPages}
onPageChange={handlePageChange}
/>
</div>
);
};
interface PaginationProps {
currentPage: number;
totalPages: number;
onPageChange: (page: number) => void;
}
const Pagination: React.FC<PaginationProps> = ({ currentPage, totalPages, onPageChange }) => {
const pages = Array.from({ length: totalPages }, (_, i) => i + 1);
return (
<div>
{currentPage > 1 && (
<button onClick={() => onPageChange(currentPage - 1)}>Previous</button>
)}
{pages.map(pageNum => (
<Link
key={pageNum}
to={`/search/${pageNum}`}
style={{ margin: '0 5px', textDecoration: 'none' }}
>
<button
key={pageNum}
onClick={() => onPageChange(pageNum)}
disabled={pageNum === currentPage}
>
{pageNum}
</button>
</Link>
))}
{currentPage < totalPages && (
<button onClick={() => onPageChange(currentPage + 1)}>Next</button>
)}
</div>
);
};
export default PeopleList;
Explanation
-
App Component (App.tsx):
- Uses
react-router-dom to set up routes for the PeopleList component.
- The
PeopleList component is set to render for /search/:page and /search routes.
-
PeopleList Component (PeopleList.tsx):
- Fetches data from the SWAPI API based on the current page using
useEffect.
- Manages state including
people, loading, error, currentPage, and totalPages.
- Updates the current page when the
page route parameter changes.
- Contains a
handlePageChange function to update the current page and navigate to the corresponding route.
- Renders a list of fetched people or shows a loading/error message based on the state.
-
Pagination Component (Pagination):
- Renders pagination controls with buttons for previous, next, and numbered pages.
- Contains a
Link component from react-router-dom to handle navigation without refreshing the page.
- Calls
onPageChange to update the current page when a pagination button is clicked.
Running Your App
Run your React application with:
npm start
You should see a list of Star Wars characters with pagination controls. Clicking the buttons should navigate between pages and update the URL to reflect the current page.
This setup ensures that the PeopleList component fetches data when the URL changes and that the pagination state is managed through the URL query parameters, enabling easy sharing of specific pages' URLs.