본문으로 바로가기 본문 바로가기
WIKI 기술 지식 베이스

Data Grid - API 객체

원문 보기 위키 갱신

Data Grid를 그 API로 제어해 봐요.

출처: MUI X documentation

본문

API 객체는 Data Grid와 프로그래밍 방식으로 상호작용하는 데 사용할 수 있는 상태와 모든 메서드를 담은 인터페이스예요.

모든 API 메서드의 목록은 GridApi 페이지에서 확인할 수 있어요.

:::warning 새롭거나 실험적인 기능은 unstable_ 접두사가 붙으며, 언제든 제거·이름 변경·재작업될 수 있어요. :::

API 객체 사용 방법

API 객체는 apiRef 변수를 통해 접근할 수 있어요. 이 변수에 접근하려면 useGridApiContext()(DataGrid 안에서) 또는 useGridApiRef()(DataGrid 밖에서)를 사용하세요.

Data Grid 안에서

컴포넌트 슬롯 안이나 렌더 안에서(예: renderCell() 또는 renderHeader()) API 객체에 접근하려면 useGridApiContext() 훅을 사용하세요. 아래 스니펫은 Grid의 GridToolbarContainer 안에 Button을 렌더링해요.

function CustomToolbar() {
  const apiRef = useGridApiContext();

  return (
    <GridToolbarContainer>
      <Button onClick={() => apiRef.current.setPage(1)}>Go to page 1</Button>
    </GridToolbarContainer>
  );
}

:::info Data Grid 컴포넌트 안에서 API 객체를 사용할 때 useGridApiRef()로 초기화할 필요는 없어요. :::

import Box from '@mui/material/Box';
import Button from '@mui/material/Button';
import { DataGrid, GridToolbarContainer, useGridApiContext } from '@mui/x-data-grid';
import { useDemoData } from '@mui/x-data-grid-generator';

function CustomToolbar() {
  const apiRef = useGridApiContext();

  const handleGoToPage1 = () => apiRef.current.setPage(1);

  return (
    <GridToolbarContainer>
      <Button onClick={handleGoToPage1}>Go to page 1</Button>
    </GridToolbarContainer>
  );
}

export default function UseGridApiContext() {
  const { data, loading } = useDemoData({
    dataSet: 'Commodity',
    rowLength: 100,
    maxColumns: 6,
  });

  return (
    <Box sx={{ height: 400, width: '100%' }}>
      <DataGrid
        {...data}
        loading={loading}
        slots={{
          toolbar: CustomToolbar,
        }}
        initialState={{
          ...data.initialState,
          pagination: {
            paginationModel: {
              pageSize: 10,
            },
          },
        }}
        showToolbar
      />
    </Box>
  );
}

Data Grid 밖에서

Data Grid 컴포넌트 밖에서 API 객체를 사용할 때는 useGridApiRef() 훅으로 초기화해야 해요. 그런 다음 DataGrid의 apiRef prop으로 전달할 수 있어요.

function CustomDataGrid(props) {
  const apiRef = useGridApiRef();

  return (
    <div>
      <Button onClick={() => apiRef.current.setPage(1)}>Go to page 1</Button>
      <DataGrid apiRef={apiRef} {...other} />
    </div>
  );
}

:::warning API 객체는 DataGrid의 다양한 플러그인들이 컴포넌트의 첫 렌더링 동안 채워 넣어요. 첫 렌더링에서 사용하려 하면 아직 모든 메서드가 등록되지 않았기 때문에 충돌이 발생할 수 있어요. :::

import * as React from 'react';
import Button from '@mui/material/Button';
import Stack from '@mui/material/Stack';
import Box from '@mui/material/Box';
import { DataGrid, useGridApiRef } from '@mui/x-data-grid';
import { useDemoData } from '@mui/x-data-grid-generator';

export default function UseGridApiRef() {
  const { data, loading } = useDemoData({
    dataSet: 'Commodity',
    rowLength: 100,
    maxColumns: 6,
  });

  const [paginationModel, setPaginationModel] = React.useState({
    page: 0,
    pageSize: 10,
  });

  const apiRef = useGridApiRef();

  const handleGoToPage1 = () => apiRef.current?.setPage(1);

  return (
    <Stack
      spacing={1}
      sx={{
        alignItems: 'flex-start',
        width: '100%',
      }}
    >
      <Button onClick={handleGoToPage1}>Go to page 1</Button>
      <Box sx={{ height: 400, width: '100%' }}>
        <DataGrid
          {...data}
          loading={loading}
          apiRef={apiRef}
          pagination
          paginationModel={paginationModel}
          onPaginationModelChange={setPaginationModel}
          pageSizeOptions={[10, 25, 50, 100]}
        />
      </Box>
    </Stack>
  );
}

일반적인 사용 사례

비활성화된 컬럼 기능 접근하기

컬럼의 비활성화된 기능(예: 숨기기, 정렬, 필터링, 고정, 그룹화 등)을 initialState, 제어 모델, 또는 API 객체를 사용해서 프로그래밍 방식으로 제어할 수 있어요.

아래 예시에서는 API 객체를 사용해서 기본 그리드 UI에서 정렬할 수 없는(colDef.sortable 속성이 false로 설정된) firstName 컬럼에 커스텀 정렬을 만드는 모습을 보여 줘요.

const columns = [{ field: 'rating', sortable: false }, ...otherColumns];

function CustomDataGrid(props) {
  const apiRef = useGridApiRef();

  return (
    <div>
      <Button onClick={() => apiRef.current.sortColumn('firstName', 'asc')}>
        Sort by ASC
      </Button>
      <Button onClick={() => apiRef.current.sortColumn('firstName', 'desc')}>
        Sort by DESC
      </Button>
      <Button onClick={() => apiRef.current.sortColumn('firstName', null)}>
        Clear sort
      </Button>
      <DataGrid columns={columns} apiRef={apiRef} {...other} />
    </div>
  );
}
import Button from '@mui/material/Button';
import Box from '@mui/material/Box';
import { DataGrid, useGridApiRef, GridColDef } from '@mui/x-data-grid';

const columns: GridColDef[] = [
  { field: 'id', headerName: 'ID', width: 90 },
  {
    field: 'firstName',
    headerName: 'First name',
    rowHeader: true,
    width: 150,
    editable: true,
    filterable: false,
    sortable: false,
  },
  {
    field: 'lastName',
    headerName: 'Last name',
    rowHeader: true,
    width: 150,
    editable: true,
  },
];

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

export default function AccessDisabledColumnFeatures() {
  const apiRef = useGridApiRef();

  return (
    <div style={{ width: '100%' }}>
      <Button onClick={() => apiRef.current?.sortColumn('firstName', 'asc')}>
        Sort by ASC
      </Button>
      <Button onClick={() => apiRef.current?.sortColumn('firstName', 'desc')}>
        Sort by DESC
      </Button>
      <Button onClick={() => apiRef.current?.sortColumn('firstName', null)}>
        Remove sort
      </Button>
      <Box sx={{ height: 400 }}>
        <DataGrid columns={columns} rows={rows} apiRef={apiRef} />
      </Box>
    </div>
  );
}

상태에서 데이터 가져오기

자세한 예시는 State—Access the state를 확인하세요.

그리드 이벤트 수신하기

자세한 예시는 Events—Subscribing to events를 확인하세요.

API

더 알아보기

더 자세한 내용은 MUI X Data Grid 문서를 참고하세요.