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

Data Grid - 현지화

원문 보기 위키 갱신

Data Grid - 현지화 (Localization)

Data Grid의 현지화 기능은 전 세계 사용자를 위한 적절한 번역과 형식을 제공합니다.

MUI X의 기본 로케일은 영어(미국)입니다. 다른 로케일을 사용하려면 아래 안내를 따르세요.

번역 키 (Translation keys)

localeText prop을 사용하여 자신만의 텍스트와 번역을 전달할 수 있습니다. 지원되는 모든 번역 키는 GitHub 저장소의 소스 코드에서 확인할 수 있습니다. 다음 예시에서는 빠른 필터(quick filter) 플레이스홀더의 라벨을 커스터마이즈합니다.

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

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

  return (
    <div style={{ height: 400, width: '100%' }}>
      <DataGrid
        {...data}
        localeText={{
          toolbarQuickFilterPlaceholder: 'Search commodities',
        }}
        showToolbar
      />
    </div>
  );
}

로케일 텍스트 (Locale text)

MUI X의 기본 로케일은 영어(미국)입니다.

테마를 사용하여 로케일 텍스트를 구성할 수 있습니다:

import { createTheme, ThemeProvider } from '@mui/material/styles';
import { DataGrid } from '@mui/x-data-grid';
import { bgBG } from '@mui/x-data-grid/locales';
// Or import { bgBG } from '@mui/x-data-grid-pro/locales';
// Or import { bgBG } from '@mui/x-data-grid-premium/locales';

const theme = createTheme(
  {
    palette: {
      primary: { main: '#1976d2' },
    },
  },
  bgBG,
);

<ThemeProvider theme={theme}>
  <DataGrid />
</ThemeProvider>;

createTheme()는 인자 수에 제한이 없습니다. 이미 핵심 컴포넌트의 번역을 사용하고 있다면 새 인자로 bgBG를 추가할 수 있습니다. Data Grid Pro는 Data Grid의 확장이므로 동일한 import가 작동합니다.

import { createTheme, ThemeProvider } from '@mui/material/styles';
import { DataGrid } from '@mui/x-data-grid';
import { bgBG } from '@mui/x-data-grid/locales';
import { bgBG as pickersBgBG } from '@mui/x-date-pickers/locales';
import { bgBG as coreBgBG } from '@mui/material/locale';

const theme = createTheme(
  {
    palette: {
      primary: { main: '#1976d2' },
    },
  },
  bgBG, // x-data-grid translations
  pickersBgBG, // x-date-pickers translations
  coreBgBG, // core translations
);

<ThemeProvider theme={theme}>
  <DataGrid />
</ThemeProvider>;

createTheme()와 ThemeProvider를 사용하지 않고 언어 번역을 Data Grid에 직접 전달하고 싶다면, @mui/x-data-grid/locales에서 언어 번역을 직접 불러올 수 있습니다.

import { DataGrid } from '@mui/x-data-grid';
import { nlNL } from '@mui/x-data-grid/locales';

<DataGrid localeText={nlNL.components.MuiDataGrid.defaultProps.localeText} />;

지원되는 로케일

import LocalisationTable from 'docs/src/modules/components/LocalizationTable';
import data from './data.json';

export default function DataGridLocalisationTableNoSnap() {
  return <LocalisationTable data={data} />;
}

소스 코드는 GitHub 저장소에서 찾을 수 있습니다.

자신만의 번역을 만들거나 영어 텍스트를 커스터마이즈하려면, 이 파일을 프로젝트에 복사하고 필요한 변경을 한 뒤 해당 위치에서 로케일을 import 하세요. Data Grid 컴포넌트의 이러한 번역들은 전체 라이브러리의 Localization 전략에 의존한다는 점에 유의하세요.

또한 pnpm l10n:llm CLI 스크립트를 실행하여 특정 패키지와 로케일의 누락된 번역을 LLM으로 번역할 수 있습니다. 인터랙티브 CLI가 번역할 패키지와 로케일을 선택하는 과정을 안내하고, 그다음 LLM이 누락된 로케일을 번역하도록 프롬프트를 생성합니다.

RTL 지원

아랍어, 페르시아어, 히브리어 같은 오른쪽에서 왼쪽(RTL) 언어가 지원됩니다. 이 언어들을 사용하려면 이 가이드를 따르세요.

아래 예시는 RTL 언어(아랍어)를 Data Grid와 함께 사용하는 방법을 보여줍니다.

import * as React from 'react';
import { prefixer } from 'stylis';
import rtlPlugin from '@mui/stylis-plugin-rtl';
import { DataGrid, GridColDef } from '@mui/x-data-grid';
import { arSD } from '@mui/x-data-grid/locales';
import createCache from '@emotion/cache';
import { CacheProvider } from '@emotion/react';
import { createTheme, ThemeProvider, useTheme } from '@mui/material/styles';

// Create rtl cache
const cacheRtl = createCache({
  key: 'data-grid-rtl-demo',
  stylisPlugins: [prefixer, rtlPlugin],
});

const columns: GridColDef[] = [
  {
    field: 'id',
    headerName: 'تعريف',
    width: 150,
  },
  {
    field: 'name',
    headerName: 'اسم',
    rowHeader: true,
    width: 150,
  },
  {
    field: 'age',
    headerName: 'عمر',
    valueGetter: (value) => `${value} سنوات`,
    width: 150,
  },
  {
    field: 'occupation',
    headerName: 'المهنة',
    width: 150,
  },
  {
    field: 'gender',
    headerName: 'جنس',
    width: 150,
  },
];

const rows = [
  { id: 1, name: 'سارہ', age: 35, occupation: 'معلم', gender: 'أنثى' },
  { id: 2, name: 'زید', age: 42, occupation: 'مهندس', gender: 'ذكر' },
  { id: 3, name: 'علی', age: 33, occupation: 'محاسب', gender: 'ذكر' },
  { id: 4, name: 'فاطمہ', age: 25, occupation: 'معلم', gender: 'أنثى' },
  { id: 5, name: 'ایندریو', age: 65, occupation: 'مهندس', gender: 'ذكر' },
];

export default function DataGridRTL() {
  // Inherit the theme from the docs site (dark/light mode)
  const existingTheme = useTheme();

  const theme = React.useMemo(
    () =>
      createTheme({}, arSD, existingTheme, {
        direction: 'rtl',
      }),
    [existingTheme],
  );
  return (
    <CacheProvider value={cacheRtl}>
      <ThemeProvider theme={theme}>
        <div dir="rtl" style={{ height: 400, width: '100%' }}>
          <DataGrid rows={rows} columns={columns} />
        </div>
      </ThemeProvider>
    </CacheProvider>
  );
}

페이징 번호 형식 (Pagination number formatting)

페이징 컴포넌트에서 큰 숫자를 형식화하려면 다음 코드로 paginationDisplayedRows를 커스터마이즈하세요:

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

// ======================================================
// TODO: replace with your locale
import { frFR as locale } from '@mui/x-data-grid/locales';
const LOCALE = 'fr-FR';
// ======================================================

function formatNumber(value: number | string) {
  if (typeof Intl !== 'undefined' && Intl.NumberFormat) {
    try {
      const result = new Intl.NumberFormat(LOCALE).format(Number(value));
      return result === 'NaN' ? String(value) : result;
    } catch {
      return String(value);
    }
  }
  return String(value);
}

function paginationDisplayedRows({
  from,
  to,
  count,
  estimated,
}: {
  from: number;
  to: number;
  count: number;
  estimated?: number;
}) {
  if (!estimated) {
    return `${formatNumber(from)}–${formatNumber(to)} sur ${
      count !== -1 ? formatNumber(count) : `plus de ${formatNumber(to)}`
    }`;
  }
  const estimatedLabel =
    estimated && estimated > to
      ? `environ ${formatNumber(estimated)}`
      : `plus de ${formatNumber(to)}`;
  return `${formatNumber(from)}–${formatNumber(to)} sur ${
    count !== -1 ? formatNumber(count) : estimatedLabel
  }`;
}

const localeText = {
  ...locale.components.MuiDataGrid.defaultProps.localeText,
  paginationDisplayedRows,
};

function App() {
  return (
    <DataGrid
      rowCount={1000000}
      localeText={localeText}
    />
  )
}
import { useDemoData } from '@mui/x-data-grid-generator';
import { DataGrid } from '@mui/x-data-grid';

// ======================================================
// TODO: replace with your locale
import { frFR as locale } from '@mui/x-data-grid/locales';

const LOCALE = 'fr-FR';
// ======================================================

function formatNumber(value: number | string) {
  if (typeof Intl !== 'undefined' && Intl.NumberFormat) {
    try {
      const result = new Intl.NumberFormat(LOCALE).format(Number(value));
      return result === 'NaN' ? String(value) : result;
    } catch {
      return String(value);
    }
  }
  return String(value);
}

function paginationDisplayedRows({
  from,
  to,
  count,
  estimated,
}: {
  from: number;
  to: number;
  count: number;
  estimated?: number;
}) {
  if (!estimated) {
    return `${formatNumber(from)}–${formatNumber(to)} sur ${
      count !== -1 ? formatNumber(count) : `plus de ${formatNumber(to)}`
    }`;
  }
  const estimatedLabel =
    estimated && estimated > to
      ? `environ ${formatNumber(estimated)}`
      : `plus de ${formatNumber(to)}`;
  return `${formatNumber(from)}–${formatNumber(to)} sur ${
    count !== -1 ? formatNumber(count) : estimatedLabel
  }`;
}

const localeText = {
  ...locale.components.MuiDataGrid.defaultProps.localeText,
  paginationDisplayedRows,
};

export default function PaginationNumberFormatting() {
  const { data } = useDemoData({
    dataSet: 'Commodity',
    rowLength: 100000,
    maxColumns: 6,
  });
  return (
    <div style={{ height: 400, width: '100%' }}>
      <DataGrid {...data} localeText={localeText} />
    </div>
  );
}

API

더 알아보기 (Learn more)