본문 바로가기

코딩

Material UI - Data Grid 사용하기 (리액트 데이터 테이블)

Material UI - Data Grid 사용하기 (리액트 데이터테이블)

 

리액트 Material UI에 jquery 데이터테이블 같은게 있나 찾아보니 비슷한 Data Grid 컴포넌트가 있었다.

참고로 Data Gird는 라이센스가 2개로 나눠져 있더라.

무료 이용가능한 MIT 라이센스와, 구매해야 쓸 수 있는 유료 라이센스.

나는 무료 라이센스 Data Grid를 사용해보았다. (유료는 제공하는 기능이 좀더 많은듯?)

Material UI - DataGrid 설치하기

// with npm
npm install @material-ui/data-grid

// with yarn
yarn add @material-ui/data-grid

위와 같이 @material-ui/data-grid 를 설치해야 사용할 수 있다.

DataGrid Import 하기

import { DataGrid } from '@material-ui/data-grid';

코드 상단에 위와 같이 import문을 추가한다.

 

DataGrid 예제 코드

mport * as React from 'react';
import { DataGrid } from '@material-ui/data-grid';

const columns = [
  { field: 'id', headerName: 'ID', width: 70 },
  { field: 'firstName', headerName: 'First name', width: 130 },
  { field: 'lastName', headerName: 'Last name', width: 130 },
  {
    field: 'age',
    headerName: 'Age',
    type: 'number',
    width: 90,
  },
  {
    field: 'fullName',
    headerName: 'Full name',
    description: 'This column has a value getter and is not sortable.',
    sortable: false,
    width: 160,
    valueGetter: (params) =>
      `${params.getValue('firstName') || ''} ${
        params.getValue('lastName') || ''
      }`,
  },
];

const rows = [
  { id: 1, lastName: 'Snow', firstName: 'Jon', age: 35 },
  { id: 2, lastName: 'Lannister', firstName: 'Cersei', age: 42 },
  { id: 3, lastName: 'Lannister', firstName: 'Jaime', age: 45 },
  { id: 4, lastName: 'Stark', firstName: 'Arya', age: 16 },
  { id: 5, lastName: 'Targaryen', firstName: 'Daenerys', age: null },
  { id: 6, lastName: 'Melisandre', firstName: null, age: 150 },
  { id: 7, lastName: 'Clifford', firstName: 'Ferrara', age: 44 },
  { id: 8, lastName: 'Frances', firstName: 'Rossini', age: 36 },
  { id: 9, lastName: 'Roxie', firstName: 'Harvey', age: 65 },
];

export default function DataGridDemo() {
  return (
    <div style={{ height: 400, width: '100%' }}>
      <DataGrid rows={rows} columns={columns} pageSize={5} checkboxSelection />
    </div>
  );
}

 

* 공식문서 : material-ui.com/components/data-grid/#mit-version

 

React Data Grid component - Material-UI

A fast and extendable data table and data grid for React. It's a feature-rich component available in MIT or Commercial versions.

material-ui.com

칼럼별 sorting도 특정 셀 선택도 가능하다. 굿!