How to use react-window Module in React JS?
React window works by only rendering part of a large data set. This module is very easy to integrate and reduces the amount of time which generally takes a while to render. This module avoids the over-allocation of DOM nodes. We can use the react-window module in React JS using the following approach.
Prerequisite:
Approach to use react-window Module:
- Component Imports: Begin by importing necessary components from React, including ListItem and ListItemText from Material-UI, as well as the FixedSizeList from the react-window library. These components will be used to construct the scrollable list.
- Row Rendering Function: Define a function, such as
renderOurRow
, responsible for rendering individual rows within the FixedSizeList. This function takes care of creating ListItem elements with dynamic content based on the item index, ensuring efficient rendering for large datasets. - Main Application Component: Create the main application component, typically named
App
. Within this component, utilize the FixedSizeList to render a list of a fixed size, specifying dimensions (height and width), item size, and the total number of items. Customize the content and appearance of each ListItem through the row rendering function.
Steps to create React Application And Installing Module:
Step 1: Create a React application using the following command.
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command.
cd foldername
Step 3: After creating the ReactJS application, Install the material-ui and react-window modules using the following command.
npm install @material-ui/core
npm install react-window
Project Structure:
The updated dependencies in package.json file will look like:
"dependencies": {
"@material-ui/core": "^4.12.4",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"react-window": "^1.8.10",
"web-vitals": "^2.1.4",
}
Example: Now write down the following code in the App.js file.
Javascript
import React from "react" ; import ListItem from "@material-ui/core/ListItem" ; import ListItemText from "@material-ui/core/ListItemText" ; import { FixedSizeList } from "react-window" ; function renderOurRow(props) { const { index } = props; return ( <ListItem key={index} button> <ListItemText primary={`Sample Item ${index + 1}`} /> </ListItem> ); } export default function App() { return ( <div style= { { display: "block" , padding: 30 } }> <h4> How to use react-window Module in ReactJS? </h4> <FixedSizeList height={250} width={300} itemSize={100} itemCount={5}> {renderOurRow} </FixedSizeList> </div> ); } |
Step to Run Application: Run the application using the following command from the root directory of the project.
npm start
Output: Now open your browser and go to http://localhost:3000
Contact Us