LoginSignup
0
1

[Nextjs]データを表形式で表示する方法![DataGrid]

Last updated at Posted at 2023-12-25

初めに

前回は、SQLiteDBからデータを取ってきて、表示する方法を紹介しました!
今回は、Material-UIのDataGridを活用し、見やすく表示する方法を紹介します!
以下の「nihongo.db」データベースの「nihongo」テーブルの情報を取ってきて、表示する手順を具体的に紹介します!

image.png

1. Material-UIのDataGridを導入する

初めに、Material-UIのDataGridをインストールします。
以下のコマンドを使用して、必要なパッケージをインストールします。

npm install @mui/x-data-grid   # Material-UIのデータグリッドコンポーネント
npm install @emotion/react    # EmotionライブラリのReactバインディング
npm install @emotion/styled   # Emotionライブラリのスタイリング用ツール

2. 実施例

以下のコードは、インストールしたDataGridを用いて見やすく表示しています。
getAllNihongoData関数にてSQLiteDBからデータを取得し、表示しています。

// pages/index.js
import React from 'react';
import { getAllNihongoData } from './api/db';
import { DataGrid } from '@mui/x-data-grid';

const columns = [
  { field: 'id', headerName: 'ID', width: 70 },
  { field: 'aiueo', headerName: 'Visitor Name', width: 150 },
];

const HomePage = ({ data }) => {
  return (
    <div>
      <h1>Next.js SSR with SQLite</h1>
      <div style={{ height: 250, width: '80%' }}>
        // ここでDataGridコンポーネントを挿入!
        <DataGrid 
          rows={data}               // 表示するデータを指定
          columns={columns}         // 表示するカラム情報を指定
          pageSize={5}              // 1ページあたりの表示行数を指定
          checkboxSelection         // チェックボックスの列を有効にする
        />
      </div>
    </div>
  );
};

export async function getServerSideProps() {
  const data = await getAllNihongoData();

  return {
    props: { data },
  };
}

export default HomePage;

image.png

まとめ

以上により、DataGridを使用して見やすくデータを表示できました!
表の調節や、表示するデータの数も調節可能なので、試してみてください!

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1