The react-virtualized package lets us display a virtualized list.
We can use it with the AutoSizer
component to create a virtualized list that resizes the item.
In this article, we’ll look at how to create automatically resizeable lists and grids with the react-virtualized library.
Installation
To install it, we run:
npm i react-virtualized
AutoSizer
We can use the AutoSizer
component to add the auto-resizable list.
For example, we can write:
import React from "react";
import { AutoSizer, List } from "react-virtualized";
import "react-virtualized/styles.css";
const list = Array(1000)
.fill(0)
.map((_, i) => i);
function rowRenderer({ key, index, style }) {
return (
<div key={key} style={style}>
{list[index]}
</div>
);
}
export default function App() {
return (
<div style={{ height: "100vh" }}>
<AutoSizer>
{({ height, width }) => (
<List
height={height}
rowCount={list.length}
rowHeight={20}
rowRenderer={rowRenderer}
width={width}
/>
)}
</AutoSizer>
</div>
);
}
We create a list with the AutoSizer
component with a render prop inside it.
We get the height
and width
from the parameter and then pass that into the List
component’s height
component to set the width and height of the list.
We set the rowHeight
prop to set the row height of each entry.
rowRendered
has a function which has the key
, index
and style
properties from the parameter and we use that to render the entry.
index
has the index of the entry.
key
has the unique key of the row.
Now when we resize the screen, we see the list resize with the screen.
Grid
We can add a grid with react-virtualize’s Grid
component.
For instance, we can write:
import React from "react";
import "react-virtualized/styles.css";
import { Grid } from "react-virtualized";
let list = [];
let inner = [];
let width = 500;
let height = 100;
let xCoord = 0;
let yCoord = 0;
for (let i = 0; i < 1000; i++) {
do {
xCoord = Math.floor(Math.random() * width);
yCoord = Math.floor(Math.random() * height);
} while ((xCoord <= 0) | (yCoord <= 0));
if (xCoord > 0 && yCoord > 0) {
inner.push(xCoord);
inner.push(yCoord);
list.push(inner);
}
inner = [];
}
function cellRenderer({ columnIndex, key, rowIndex, style }) {
return (
<div key={key} style={style}>
{list[rowIndex][columnIndex]}
</div>
);
}
export default function App() {
return (
<div>
<Grid
cellRenderer={cellRenderer}
columnCount={list[0].length}
columnWidth={100}
height={300}
rowCount={list.length}
rowHeight={30}
width={300}
/>
</div>
);
}
We have the data in the list
nested array.
The cellRenderer
component lets us render the nested array into the grid.
We also set the columnCount
to the length of the first nested array.
And we set the columnWidth
to set the column width.
The height
is the height of the grid.
rowCount
has the row count.
rowHeight
has the row height.
width
has the grid width.
Then we see the nested list rendered on the screen.
Conclusion
We can create an auto-resizable list and grids with the react-virtualized library.