This article will discuss pagination and infinite scrolling. These concepts are commonly used in web applications to enhance the user experience. Pagination and infinite scrolling both help in the efficient handling of huge data sizes.
Approach to Implement Pagination and Infinite Scrolling:
Pagination:
- Three state variables to maintain - page, numberOfPages, data
- const [page, setPage] = useState(1) - to manage current page
- const [numberOfPages, setNumberOfPages] = useState(0) - to manage total number of pages
- const [data, setData] = useState([]) - to manage the data for the current page
- Get data from the data file or api inside useEffect() hook using callback function
- Add page and numberOfPages as dependency in useEffect() hook
- onClick() function on next and previous button to move to different pages
- Previous button should be disabled when user is on first page
- Next button should disabled when user is on last page
- Data received from file or api are to be mapped to specific UI Element
- Add CSS styles
Infinite Scrolling:
- Four state variables to maintain - loadedData, page, moreData, loading
- const [loadedData, setLoadedData] = useState([]) - to manage already loaded data
- const [page, setPage] = useState(1) - to manage current page
- const [moreData, setMoreData] = useState(true) - to check if response has more data or not
- const [loading, setLoading] = useState(false) - to track whether data has fully loaded or not
- useEffect() used for two purpose -
- to set values of state variables
- to add event listener to the scroll event
- Fetch more data when user scrolls to the end of the page
- Map the fetched data to specific UI Elements
- Add CSS Styles
Steps to Create the React App:
Step 1: Create new react app
npx create-react-app pagination-and-infinite-scrolling
Step 2: Change the directory
cd pagination-and-infinite-scrolling
Step 3: Install the required dependencies
npm install <package-name>
Step 4: Create components folder and utils folder inside src directory
cd src
mkdir components
mkdir utils
Step 5: Create Pagination.jsx and InfiniteScrolling.jsx inside the components folder
Project Structure:
The updated dependencies in package.json file will look like:
"dependencies": {
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
}
Example: Below is the code example for Pagination:
.container {
display: flex;
flex-direction: column;
justify-content: left;
width: 30%;
color: darkslategrey;
border: 1px solid black;
}
.list-item {
border-bottom: 1px solid black;
}
.list-item-span1 {
display: inline-flex;
flex-direction: column;
justify-content: space-evenly;
border-right: 1px solid black;
width: 50%;
}
.list-item-span2 {
padding-bottom: 0.07rem;
width: 50%;
}