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

Data Grid - 레이아웃

원문 보기 위키 갱신

Data Grid - 레이아웃 (Layout)

Data Grid는 여러 가지 레이아웃 모드를 제공합니다.

출처: MUI X documentation

본문

:::error Data Grid에는 고유한 크기가 없습니다. 아래 접근 방식 중 하나로 크기를 설정하지 않으면 제대로 표시되지 않을 수 있어요. 기본적으로 Data Grid는 부모 컨테이너의 공간을 채우므로, 해당 컨테이너는 고유한 크기를 가져야 합니다. 즉, 컨테이너에 자식 요소가 없어도 여전히 0이 아닌 크기를 가져야 해요. :::

플렉스 부모 컨테이너 (Flex parent container)

:::success 사용 시기:

  • Data Grid가 콘텐츠 높이를 가지되, 최소 또는 최대 높이 제약이 있도록 하고 싶을 때
  • Data Grid 높이를 동적으로 유지하고, 행이 Data Grid 뷰포트에 맞지 않을 때 행 가상화를 사용하고 싶을 때

사용하지 않을 때:

  • Data Grid가 항상 콘텐츠의 높이를 가지도록 하고, 세로 스크롤바도 없고, 행 가상화도 없게 하려면 이 경우에는 autoHeight prop을 사용하세요.

:::

Data Grid는 flex-direction: column인 플렉스 컨테이너 안에 배치할 수 있어요. 최소·최대 높이를 설정하지 않으면 Data Grid는 모든 행을 표시하는 데 필요한 만큼의 공간을 차지합니다.

:::warning 플렉스 부모 컨테이너에 maxHeight를 설정하는 것을 고려하세요. 그렇지 않으면 행 가상화가 DOM에 렌더링되는 요소 수를 제한해 성능을 개선할 수 없습니다. :::

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

export default function FlexGrid() {
  const [nbRows, setNbRows] = React.useState(3);
  const removeRow = () => setNbRows((x) => Math.max(0, x - 1));
  const addRow = () => setNbRows((x) => Math.min(100, x + 1));

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

  return (
    <Box sx={{ width: '100%' }}>
      <Stack direction="row" spacing={1} sx={{ mb: 1 }}>
        <Button size="small" onClick={removeRow}>
          Remove a row
        </Button>
        <Button size="small" onClick={addRow}>
          Add a row
        </Button>
      </Stack>
      <div style={{ display: 'flex', flexDirection: 'column' }}>
        <DataGrid {...data} rows={data.rows.slice(0, nbRows)} loading={loading} />
      </div>
    </Box>
  );
}

최소 및 최대 높이 (Minimum and maximum height)

아래 데모에서 Data Grid는 최소 높이 200px, 최대 높이 400px인 플렉스 컨테이너 안에 배치되며, 행 수가 변할 때 높이를 조정합니다.

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

const minHeight = 200;
const maxHeight = 400;

export default function MinMaxHeightGrid() {
  const [nbRows, setNbRows] = React.useState(3);
  const removeRow = () => setNbRows((x) => Math.max(0, x - 1));
  const addRow = () => setNbRows((x) => Math.min(100, x + 1));
  const containerRef = React.useRef<HTMLDivElement | null>(null);

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

  return (
    <Box sx={{ width: '100%' }}>
      <Stack direction="row" spacing={1} sx={{ mb: 1 }}>
        <Button size="small" onClick={removeRow}>
          Remove a row
        </Button>
        <Button size="small" onClick={addRow}>
          Add a row
        </Button>
      </Stack>
      <div style={{ position: 'relative' }} ref={containerRef}>
        <div
          style={{
            display: 'flex',
            flexDirection: 'column',
            maxHeight,
            minHeight,
          }}
        >
          <DataGrid {...data} rows={data.rows.slice(0, nbRows)} loading={loading} />
        </div>

        {/** Visualize max and min container height */}
        <ContainerMeasurements containerRef={containerRef} />
      </div>
    </Box>
  );
}

function ContainerMeasurements({
  containerRef,
}: {
  containerRef: React.RefObject<HTMLDivElement | null>;
}) {
  const [containerHeight, setContainerHeight] = React.useState(0);

  React.useEffect(() => {
    const target = containerRef.current;
    const observer = new ResizeObserver((entries) => {
      setContainerHeight(entries[0].contentRect.height);
    });
    if (target) {
      observer.observe(target);
    }
    return () => {
      observer.disconnect();
    };
  }, [containerRef]);

  const label = `${containerHeight}px`;

  if (containerHeight === 0) {
    return null;
  }

  return (
    <Box
      sx={(theme) => ({
        position: 'absolute',
        top: 0,
        left: -20,
        width: 20,
        height: containerHeight,
        borderColor: theme.palette.text.secondary,
        borderStyle: 'dashed',
        borderTopWidth: 1,
        borderRightWidth: 0,
        borderBottomWidth: 1,
        borderLeftWidth: 1,
      })}
    >
      <Typography
        sx={(theme) => ({
          position: 'absolute',
          top: '50%',
          left: 0,
          transform: 'rotate(180deg) translate(0, 50%)',
          writingMode: 'vertical-lr',
          color: theme.palette.text.secondary,
          textWrap: 'nowrap',
          lineHeight: 1.2,
          fontSize: '15px',
        })}
      >
        {label}
      </Typography>
    </Box>
  );
}

백분율 크기 (Percentage dimensions)

높이나 너비에 백분율(%)을 사용할 때는 Data Grid의 부모 컨테이너가 고유한 크기를 가져야 합니다. 브라우저는 부모 크기의 백분율을 기준으로 요소를 조정해요. 부모에 크기가 없으면 백분율은 0이 됩니다.

미리 정의된 크기 (Predefined dimensions)

Data Grid의 부모에 크기를 미리 정의할 수 있어요.

import { DataGrid } from '@mui/x-data-grid';
import { useDemoData } from '@mui/x-data-grid-generator';

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

  return (
    <div style={{ width: '100%' }}>
      <div style={{ height: 350, width: '100%' }}>
        <DataGrid {...data} />
      </div>
    </div>
  );
}

Height prop

height prop을 사용해 명시적 높이를 가진 부모 요소 없이 Data Grid에 직접 고정 높이를 설정할 수 있어요. 픽셀 단위 숫자, '50vh' 같은 CSS 길이, 백분율, 또는 'calc(100vh - 200px)' 같은 계산식을 받습니다. 백분율 값은 명시적 높이를 가진 부모 요소가 필요합니다. 콘텐츠 기반 크기 조정이 필요하면, 이 prop이 지원하지 않는 'auto', 'min-content', 'max-content', 'fit-content' 같은 값 대신 플렉스 부모 컨테이너를 사용하세요. 높이를 바꿀 때는 sx나 style 대신 prop을 업데이트하세요. prop이 최소 및 최대 높이도 설정하기 때문입니다.

import { DataGrid } from '@mui/x-data-grid';
import { useDemoData } from '@mui/x-data-grid-generator';

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

  return <DataGrid {...data} height={350} />;
}

:::warning height prop은 autoHeight와 함께 사용할 수 없습니다. :::

오버레이 높이 (Overlay height)

데이터 그리드에 콘텐츠가 없으면 "Loading"이나 "No rows" 같은 오버레이는 기본적으로 두 행의 높이를 차지합니다.

오버레이 높이를 커스터마이즈하려면 --DataGrid-overlayHeight CSS 변수를 사용하세요.

import Box from '@mui/material/Box';
import { DataGrid } from '@mui/x-data-grid';
import { styled } from '@mui/material/styles';

const StyledGridOverlay = styled('div')(({ theme }) => ({
  display: 'flex',
  flexDirection: 'column',
  alignItems: 'center',
  justifyContent: 'center',
  height: '100%',
  '& .no-rows-primary': {
    fill: '#3D4751',
    ...theme.applyStyles('light', {
      fill: '#AEB8C2',
    }),
  },
  '& .no-rows-secondary': {
    fill: '#1D2126',
    ...theme.applyStyles('light', {
      fill: '#E8EAED',
    }),
  },
}));

function CustomNoRowsOverlay() {
  return (
    <StyledGridOverlay>
      <svg
        fill="none"
        width={96}
        viewBox="0 0 452 257"
        aria-hidden
        focusable="false"
      >
        <path
          className="no-rows-primary"
          d="M348 69c-46.392 0-84 37.608-84 84s37.608 84 84 84 84-37.608 84-84-37.608-84-84-84Zm-104 84c0-57.438 46.562-104 104-104s104 46.562 104 104-46.562 104-104 104-104-46.562-104-104Z"
        />
        <path
          className="no-rows-primary"
          d="M308.929 113.929c3.905-3.905 10.237-3.905 14.142 0l63.64 63.64c3.905 3.905 3.905 10.236 0 14.142-3.906 3.905-10.237 3.905-14.142 0l-63.64-63.64c-3.905-3.905-3.905-10.237 0-14.142Z"
        />
        <path
          className="no-rows-primary"
          d="M308.929 191.711c-3.905-3.906-3.905-10.237 0-14.142l63.64-63.64c3.905-3.905 10.236-3.905 14.142 0 3.905 3.905 3.905 10.237 0 14.142l-63.64 63.64c-3.905 3.905-10.237 3.905-14.142 0Z"
        />
        <path
          className="no-rows-secondary"
          d="M0 10C0 4.477 4.477 0 10 0h380c5.523 0 10 4.477 10 10s-4.477 10-10 10H10C4.477 20 0 15.523 0 10ZM0 59c0-5.523 4.477-10 10-10h231c5.523 0 10 4.477 10 10s-4.477 10-10 10H10C4.477 69 0 64.523 0 59ZM0 106c0-5.523 4.477-10 10-10h203c5.523 0 10 4.477 10 10s-4.477 10-10 10H10c-5.523 0-10-4.477-10-10ZM0 153c0-5.523 4.477-10 10-10h195.5c5.523 0 10 4.477 10 10s-4.477 10-10 10H10c-5.523 0-10-4.477-10-10ZM0 200c0-5.523 4.477-10 10-10h203c5.523 0 10 4.477 10 10s-4.477 10-10 10H10c-5.523 0-10-4.477-10-10ZM0 247c0-5.523 4.477-10 10-10h231c5.523 0 10 4.477 10 10s-4.477 10-10 10H10c-5.523 0-10-4.477-10-10Z"
        />
      </svg>
      <Box sx={{ mt: 2 }}>No rows</Box>
    </StyledGridOverlay>
  );
}

export default function GridOverlayHeight() {
  return (
    <Box sx={{ width: '100%', display: 'flex', flexDirection: 'column' }}>
      <DataGrid
        columns={[
          { field: 'ID' },
          { field: 'First name', rowHeader: true },
          { field: 'Last name', rowHeader: true },
        ]}
        rows={[]}
        slots={{ noRowsOverlay: CustomNoRowsOverlay }}
        sx={{ '--DataGrid-overlayHeight': '300px' }}
      />
    </Box>
  );
}

자동 높이 (Auto height)

:::success 사용 시기:

  • Data Grid에 최소 또는 최대 높이를 설정할 필요가 없을 때
  • Data Grid가 항상 콘텐츠의 높이를 가지도록 하고, 세로 스크롤바도 없고, 행 가상화도 없게 하려고 할 때

사용하지 않을 때:

  • Data Grid에 최소 또는 최대 높이를 설정해야 하거나, Data Grid 높이를 동적으로 유지하려고 할 때 이 경우에는 플렉스 부모 컨테이너를 사용하세요.

:::

autoHeight prop을 사용하면 Data Grid가 콘텐츠에 따라 크기를 조정할 수 있어요. 즉, Data Grid의 높이는 행 수에 의해 결정되며, 모든 행이 동시에 사용자에게 보이도록 보장합니다.

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

export default function AutoHeightGrid() {
  const [nbRows, setNbRows] = React.useState(3);
  const removeRow = () => setNbRows((x) => Math.max(0, x - 1));
  const addRow = () => setNbRows((x) => Math.min(100, x + 1));

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

  return (
    <Box sx={{ width: '100%' }}>
      <Stack direction="row" spacing={1} sx={{ mb: 1 }}>
        <Button size="small" onClick={removeRow}>
          Remove a row
        </Button>
        <Button size="small" onClick={addRow}>
          Add a row
        </Button>
      </Stack>
      <DataGrid
        autoHeight
        {...data}
        loading={loading}
        rows={data.rows.slice(0, nbRows)}
      />
    </Box>
  );
}

API

더 알아보기 (Learn more)