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

Charts - useLegend

원문 보기 위키 갱신

커스텀 범례(legend) 컴포넌트를 만들기 위한 포맷된 범례 데이터를 가져옵니다.

본문

useLegend() 훅은 커스텀 범례 컴포넌트를 만드는 데 사용할 수 있는 포맷된 범례 데이터를 반환합니다.

사용법

import { useLegend } from '@mui/x-charts/hooks';

function CustomLegend() {
  const { items } = useLegend();
  // items: Array of legend items with id, label, color, markType
}
import { useLegend } from '@mui/x-charts/hooks';
import { PieChart } from '@mui/x-charts/PieChart';

const data = [
  { id: 0, value: 10, label: 'Series A' },
  { id: 1, value: 15, label: 'Series B' },
  { id: 2, value: 20, label: 'Series C' },
];

function BasicUseLegendExample() {
  const { items } = useLegend();

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
      <h4>Legend Items from useLegend:</h4>
      <ul style={{ margin: 0, padding: 0, listStyle: 'none' }}>
        {items.map((item) => (
          <li
            key={`${item.seriesId}-${item.dataIndex}`}
            style={{ display: 'flex', alignItems: 'center', gap: 8 }}
          >
            <div
              style={{
                width: 16,
                height: 16,
                backgroundColor: item.color,
                borderRadius: 4,
                transform: 'rotate(45deg) skew(-10deg, -10deg)',
              }}
            />
            <span>{item.label}</span>
          </li>
        ))}
      </ul>
    </div>
  );
}

export default function UseLegend() {
  return (
    <PieChart
      series={[{ data }]}
      height={200}
      slots={{ legend: BasicUseLegendExample }}
    />
  );
}

반환 값

useLegend()는 다음 구조의 객체를 반환합니다:

{
  items: LegendItemParams[]
}

LegendItemParams 인터페이스가 각 범례 항목의 구조를 정의합니다.

주의사항

이 훅은 차트 컨텍스트 안에서만 사용할 수 있습니다. 사용 요구사항은 hooks overview를 참고하세요.

더 알아보기

출처: MUI X documentation