React.js ライブラリ「react-cool-virtual」を使って大きなデータセットをレンダリングする
ライブラリ「react-cool-virtual」をインストールすると、大きなデータセットをレンダリングすることが可能です。ここでは、react.jsでboring-avatarsを利用するための手順と簡単な使い方を記述してます。
環境
- OS Rocky Linux release 8.4 (Green Obsidian)
- node v14.17.3
- npm 7.19.1
- yarn 1.22.10
- React 17.0.2
react.js環境構築
下記のコマンドで構築してます。ここでは、react-appという名前でプロジェクトを作成してます。
yarn global add create-react-app
npx create-react-app react-app
react-cool-virtualインストール
作成したプロジェクトに移動して、インストールします。
## 作成したプロジェクトに移動
cd react-app
## インストール
yarn add react-cool-virtual
react-cool-virtual使い方
srcディレクトリにsample.jsと名前で、以下のコードを記述します。
import React from 'react'
import useVirtual from 'react-cool-virtual'
const Sample = () => {
const { outerRef, innerRef, items } = useVirtual({
itemCount: 10000,
itemSize: 50,
});
return (
<div
ref={outerRef}
style={{ width: "300px", height: "500px", overflow: "auto" }} >
<div ref={innerRef}>
{items.map(({ index, size }) => (
<div key={index} style={{ height: `${size}px` }}>
⭐️ {index}
</div>
))}
</div>
</div>
);
};
export default Sample;
次に、srcディレクトリ配下にあるApp.jsを下記のように編集します。
import React from 'react';
import Sample from './sample';
import './App.css';
function App() {
const style = {
width: "30%",
margin: "0 auto",
marginTop: 250,
};
return (
<div className="App">
<div style={style}>
<Sample />
</div>
</div>
);
}
export default App;
実行します。
yarn start
ブラウザから http://プライベートIP:3000にアクセスすると、大量のデータセットがレンダリングされていることが確認できます。
-
前の記事
Vue.js v-on:mousedownとv-on:mouseupとv-on:clickのイベント実行順序を確認する 2022.02.20
-
次の記事
jquery エラー「Uncaught Error: Syntax error, unrecognized expression: a[href^=#]」の解決方法 2022.02.20
コメントを書く