0% found this document useful (0 votes)
2 views

React exp 004

The document presents a React component called PaginatedUsers that fetches and displays a list of users from an external JSON API. It includes functionality for pagination, allowing users to navigate through the user list with 'Previous' and 'Next' buttons. The component handles loading states and errors during data fetching using React hooks.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

React exp 004

The document presents a React component called PaginatedUsers that fetches and displays a list of users from an external JSON API. It includes functionality for pagination, allowing users to navigate through the user list with 'Previous' and 'Next' buttons. The component handles loading states and errors during data fetching using React hooks.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 4

Experiment -04

Title: Create a React component that renders dynamic content fetched from an external data source,
such as a JSON API.

Code :

1.PaginatedUsers.jsx

import React, { useState, useEffect } from "react";

import axios from "axios";

import ‘./PaginatedUsers.css’;

const PaginatedUsers = () => {

const [users, setUsers] = useState([]);

const [loading, setLoading] = useState(false);

const [error, setError] = useState("");

const [currentPage, setCurrentPage] = useState(1);

const usersPerPage = 5;

const fetchUsers = async (page) => {

setLoading(true);

setError("");

try {

const response = await axios.get(`https://jsonplaceholder.typicode.com/users`);

const startIndex = (page - 1) * usersPerPage;

const endIndex = page * usersPerPage;

setUsers(response.data.slice(startIndex, endIndex));

setLoading(false);

} catch (err) {

setLoading(false);

setError("Failed to fetch data. Please try again.");

};
useEffect(() => {

fetchUsers(currentPage);

}, [currentPage]);

return (

<Container>

<h2>🌍 User List</h2>

{loading && <p>Loading...</p>}

{error && <p style={{ color: "red" }}>{error}</p>}

<UserList>

{users.map((user) => (

<UserItem key={user.id}>

<h3>{user.name}</h3>

<p>{user.email}</p>

</UserItem>

))}

</UserList>

<div>

<Button onClick={() => setCurrentPage((prev) => prev - 1)} disabled={currentPage === 1}>

Previous

</Button>

<Button onClick={() => setCurrentPage((prev) => prev + 1)}>Next</Button>

</div>

</Container>

);

};

export default PaginatedUsers;


2.App.jsx

import PaginatedUsers from "./components/PaginatedUsers"

function App() {

return (

<>

<PaginatedUsers/>

</>

export default App

Output:

You might also like