DataGrid コンポーネントに Global Style Overrides を適用しようとしたら MuiDataGrid がないよ、と怒られた時の対処法

2022.03.01

この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。

検証環境

言語・ライブラリ Version
React 17.0.2
Typescript 4.4.3
MUI 5.4.1
emotion 11.7.1

事象

emotion のThemeProviderを使って Global Theme を定義しています。

このプロジェクトには複数の DataGrid テーブルが含まれるため、theme.ts に DataGrid の Global CSS を追加したいと考えました。

コンポーネントの Global Style を上書きするには通常以下のような記述になります。

theme.ts

import { createTheme, ThemeOptions } from '@mui/material/styles'

const defaultStyle: ThemeOptions = {
    ...
    components: {
        // Name of the component
        MuiButton: {
        styleOverrides: {
            // Name of the slot
            root: {
            // Some CSS
            fontSize: '1rem',
            },
        },
        },
    },
}

export default createTheme({
  ...defaultStyle,
})

index.tsx

import {ThemeProvider} from "@emotion/react";
import {CssBaseline} from "@mui/material";
import React from "react";
import ReactDOM from "react-dom";
import {App} from "./App";
import theme from "./theme";

ReactDOM.render(
  <React.StrictMode>
    <ThemeProvider theme={theme}>
      <CssBaseline />
      <App />
    </ThemeProvider>
  </React.StrictMode>,
  document.getElementById("root"),
);

しかし、ドキュメントに沿って ThemeOptionsのcomponent に MuiDataGrid を指定したところ以下のエラーになりました。

Error: Type '{ MuiDataGrid: { styleOverrides: { root: { borderColor: string; '& .MuiDataGrid-columnHeaders': { borderBottomColor: string; }; '& .MuiDataGrid-cell': { borderBottomColor: string; }; }; }; }; }' is not assignable to type 'Components'. Object literal may only specify known properties, and 'MuiDataGrid' does not exist in type 'Components'.ts(2322)

何が足りないか

ドキュメントをよく読むと以下の記述がありました。

Internally, it uses module augmentation to extend the default theme structure with the extension components available in the lab.

どうやら Lab Component の Global Theme をカスタマイズしたい場合は augmentation module の型をインポートしてあげる必要があったようです。

// TypeScript 4.x 以上
import type {} from "@mui/lab/themeAugmentation";
// TypeScript 3.x 以下
import "@mui/lab/themeAugmentation";

対処法

以下のようにthemeAugmentationの型をインポートしてあげることでエラーを解消しました。

import {createTheme, ThemeOptions} from "@mui/material/styles";
import type {} from "@mui/x-data-grid/themeAugmentation";

const defaultStyle: ThemeOptions = {
  components: {
    MuiDataGrid: {
      styleOverrides: {
        root: {
          borderColor: "rgb(226, 224, 222)",
          "& .MuiDataGrid-columnHeaders": {
            borderBottomColor: "rgb(226, 224, 222)",
          },
          "& .MuiDataGrid-cell": {
            borderBottomColor: "rgb(226, 224, 222)",
          },
        },
      },
    },
  },
};

export default createTheme({
  ...defaultStyle,
});

References