We often have to render large lists in React apps.
In this article, we’ll look at ways to render large lists in React apps.
Virtual Scrolling
The react-virtualized library lets us add a virtualized list into our React app.
It only loads data that is shown on the screen.
To use it, we install it by running:
npm i react-virtualized
Then we can use it bu writing:
import React from "react";
import { List } from "react-virtualized";
export default function App() {
const data = new Array(1000).fill().map((value, id) => ({
id: id,
title: id,
body: id
}));
const renderRow = ({ index, key, style }) => (
<div>
<div key={key} style={style} className="post">
<h3>{data[index].title}</h3>
<p>item {data[index].body}</p>
</div>
</div>
);
return (
<List
width={window.innerWidth * 0.95}
height={300}
rowRenderer={renderRow}
rowCount={data.length}
rowHeight={120}
/>
);
}
We just create the renderRiw function to render the items by their index and style .
The style is computed by react-virtualized to fit the data in the list.
We get the row from data[index] .
rowCount is set to the total row count.
height has the height of the list.
rowHeight has the row’s height.
react-window
The react-window is another virtualized scrolling component.
To install it, we run:
npm i react-window
Then we can add the list by writing:
import React from "react";
import { FixedSizeList as List } from "react-window";
export default function App() {
const data = new Array(1000).fill().map((value, id) => ({
id: id,
title: id,
body: id
}));
const Row = ({ index, key, style }) => (
<div>
<div key={key} style={style} className="post">
<h3>{data[index].title}</h3>
<p>item {data[index].body}</p>
</div>
</div>
);
return (
<List
width={window.innerWidth * 0.95}
height={300}
itemCount={data.length}
itemSize={120}
>
{Row}
</List>
);
}
We have the Row component that has the row data.
It’s the same as the previous example’s renderRow function.
We have the List component with the width and height so it can compute the row sizes.
itemSize has the row’s height.
itemCount has the number of items to render.
react-window is faster and smaller than react-virtualized .
Conclusion
We can render large lists with virtual scrolling.