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

Rich Tree View - 가상화(Virtualization)

원문 보기 위키 갱신

Tree View에서 대용량 데이터셋을 처리해요.

출처: MUI X documentation

본문

기본 사용법

가상화는 <RichTreeViewPro /> 컴포넌트에서 기본적으로 활성화돼 있어요. 다음은 100,000개 항목이 있는 Tree View의 예시예요:

import Box from '@mui/material/Box';
import { TreeViewDefaultItemModelProperties } from '@mui/x-tree-view/models';
import { RichTreeViewPro } from '@mui/x-tree-view-pro/RichTreeViewPro';

const items: TreeViewDefaultItemModelProperties[] = Array.from(
  { length: 100 },
  (_1, i) => ({
    id: `item-${i + 1}`,
    label: `Item ${i + 1}`,
    children: Array.from({ length: 100 }, (_2, j) => ({
      id: `item-${i + 1}-${j + 1}`,
      label: `Item ${i + 1}-${j + 1}`,
      children: Array.from({ length: 10 }, (_3, k) => ({
        id: `item-${i + 1}-${j + 1}-${k + 1}`,
        label: `Item ${i + 1}-${j + 1}-${k + 1}`,
      })),
    })),
  }),
);

const defaultExpandedItems = items.flatMap((el) => [
  el.id,
  ...(el.children ?? []).map((child) => child.id),
]);

export default function BasicVirtualizedRichTreeViewPro() {
  return (
    <Box sx={{ height: 352, minWidth: 250 }}>
      <RichTreeViewPro items={items} defaultExpandedItems={defaultExpandedItems} />
    </Box>
  );
}

disableVirtualization prop을 사용해 가상화를 비활성화할 수 있어요:

<RichTreeViewPro items={ITEMS} disableVirtualization />

가상화를 비활성화해도 <RichTreeViewPro />의 기본 평면(flat) DOM 구조는 바뀌지 않아요. 중첩(nested) DOM 구조가 필요하다면, 예를 들어 groupTransition 슬롯을 기반으로 한 펼침 애니메이션을 사용하려면 disableVirtualization과 domStructure="nested"를 모두 설정하세요:

<RichTreeViewPro items={ITEMS} disableVirtualization domStructure="nested" />

항목 높이(Item height)

가상화가 활성화되면 Tree View는 어떤 항목이 보이는지 계산하기 위해 각 항목의 높이를 알아야 해요. 제공하지 않으면 itemHeight prop은 기본적으로 32px로 설정돼요.

다른 값을 전달해 항목 높이를 커스터마이징할 수 있어요:

<RichTreeViewPro items={ITEMS} itemHeight={48} />

:::warning 가상화는 itemHeight={null}과 호환되지 않아요. 항목의 높이가 서로 다르다면 disableVirtualization prop을 사용해 가상화를 비활성화해야 해요. :::

자세한 내용은 Item height 문서를 참고하세요.

DOM 구조

가상화는 트리에서의 계층 구조와 관계없이 모든 항목이 형제로 렌더링되는 평면 DOM 구조를 요구해요. <RichTreeViewPro />는 기본적으로 domStructure="flat"을 사용해요. 가상화가 활성화된 동안에는 중첩 DOM 구조가 지원되지 않아요.

<ul>
  <li>Item 1</li>
  <li>Item 1.1</li>
  <li>Item 1.2</li>
  <li>Item 2</li>
</ul>

자세한 내용은 DOM 구조 문서를 참고하세요.

레이아웃

:::error 가상화가 활성화되면 Tree View에는 고유한(내재적) 치수가 없어요: 아래 방법 중 하나로 치수를 설정해야 하며, 그렇지 않으면 올바르게 표시되지 않을 수 있어요. 기본적으로 가상화된 Tree View는 부모 컨테이너의 공간을 채우므로, 그 컨테이너에는 고유한 치수가 있어야 해요. 즉, 컨테이너에 자식 요소가 없어도 0이 아닌 치수를 가져야 해요. :::

플렉스 부모 컨테이너

:::success 이런 경우에 사용하세요:

  • Tree View가 콘텐츠의 높이를 가지되, 최소 또는 최대 높이 제한이 있게 하고 싶을 때.
  • Tree View 높이를 동적으로 만들고, 항목이 Tree View 뷰포트에 맞지 않을 때 항목 가상화를 사용하고 싶을 때.

이런 경우에는 사용하지 마세요:

  • Tree View가 항상 콘텐츠의 높이를 가지도록 하고, 세로 스크롤바도 없고, 항목 가상화도 없게 하고 싶을 때. 이런 경우 disableVirtualization prop을 사용하세요.

:::

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

:::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 { RichTreeViewPro } from '@mui/x-tree-view-pro/RichTreeViewPro';
import { TreeViewDefaultItemModelProperties } from '@mui/x-tree-view/models';

const INITIAL_ITEMS: TreeViewDefaultItemModelProperties[] = Array.from(
  { length: 100 },
  (_1, i) => ({
    id: `item-${i + 1}`,
    label: `Item ${i + 1}`,
  }),
);

export default function FlexRichTreeView() {
  const [nbItems, setNbItems] = React.useState(3);
  const removeItem = () => setNbItems((x) => Math.max(0, x - 1));
  const addItem = () => setNbItems((x) => Math.min(100, x + 1));

  return (
    <Box sx={{ width: '100%' }}>
      <Stack direction="row" spacing={1} sx={{ mb: 1 }}>
        <Button size="small" onClick={removeItem}>
          Remove an item
        </Button>
        <Button size="small" onClick={addItem}>
          Add an item
        </Button>
      </Stack>
      <div style={{ display: 'flex', flexDirection: 'column' }}>
        <RichTreeViewPro items={INITIAL_ITEMS.slice(0, nbItems)} />
      </div>
    </Box>
  );
}

최소 및 최대 높이

아래 데모에서 Tree View는 최소 높이 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 { RichTreeViewPro } from '@mui/x-tree-view-pro/RichTreeViewPro';
import Typography from '@mui/material/Typography';
import { TreeViewDefaultItemModelProperties } from '@mui/x-tree-view/models';

const minHeight = 200;
const maxHeight = 400;

const INITIAL_ITEMS: TreeViewDefaultItemModelProperties[] = Array.from(
  { length: 100 },
  (_1, i) => ({
    id: `item-${i + 1}`,
    label: `Item ${i + 1}`,
  }),
);

export default function MinMaxHeightRichTreeView() {
  const [nbItems, setNbItems] = React.useState(3);
  const containerRef = React.useRef<HTMLDivElement | null>(null);
  const removeItem = () => setNbItems((x) => Math.max(0, x - 1));
  const addItem = () => setNbItems((x) => Math.min(100, x + 1));

  return (
    <Box sx={{ width: '100%' }}>
      <Stack direction="row" spacing={1} sx={{ mb: 1 }}>
        <Button size="small" onClick={removeItem}>
          Remove an item
        </Button>
        <Button size="small" onClick={addItem}>
          Add an item
        </Button>
      </Stack>
      <div style={{ position: 'relative' }} ref={containerRef}>
        <div
          style={{
            display: 'flex',
            flexDirection: 'column',
            maxHeight,
            minHeight,
          }}
        >
          <RichTreeViewPro items={INITIAL_ITEMS.slice(0, nbItems)} />
        </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>
  );
}

백분율 치수

높이나 너비에 백분율(%)을 사용할 때는 Tree View의 부모 컨테이너가 고유한 치수를 갖도록 하세요. 브라우저는 요소를 부모 크기의 백분율로 조정해요. 부모에 크기가 없으면 백분율은 0이 돼요.

사전 정의된 치수

Tree View의 부모에 치수를 미리 정의할 수 있어요.

import { RichTreeViewPro } from '@mui/x-tree-view-pro/RichTreeViewPro';
import { TreeViewDefaultItemModelProperties } from '@mui/x-tree-view/models';

const INITIAL_ITEMS: TreeViewDefaultItemModelProperties[] = Array.from(
  { length: 5 },
  (_1, i) => ({
    id: `item-${i + 1}`,
    label: `Item ${i + 1}`,
  }),
);

export default function FixedSizeRichTreeView() {
  return (
    <div style={{ width: '100%' }}>
      <div style={{ height: 350, width: '100%' }}>
        <RichTreeViewPro items={INITIAL_ITEMS} />
      </div>
    </div>
  );
}