LoginSignup
5
9

Material-UI でデフォルトテーマをカスタマイズする方法

Last updated at Posted at 2021-01-17

概要

React とセットで使うことの多い Material-UI のテーマをカスタマイズする方法です。
デフォルトテーマは『こちら』を参照してください。

テーマをカスタマイズ

ここではtheme.jsというファイルを作成します。

theme.js
import { createMuiTheme } from '@material-ui/core/styles';

// フォントを設定
const fontFamily = [
  'Noto Sans JP',
  'メイリオ',
  'MS Pゴシック',
  'sans-serif',
  // 使用したいフォントを以降に羅列してください
].join(',');

/*****************
 * テーマを設定
 *****************
 */
const theme = createMuiTheme({
  typography: {
    fontFamily: fontFamily,  // フォント
  },
  palette: {
    // Primaryカラーを設定
    primary: {
      light: '#54C527',
      main: '#ff9800',
      dark: '#b26a00',
      contrastText: '#000000',
      mainGradient: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)',
    },
    // Secondaryカラーを設定
    secondary: {
      light: '#33eb91',
      main: '#00e676',
      dark: '#00a152',
      contrastText: '#ffffff',
    },
    type: 'dark', // ダークモードをON
  },
  mixins: {
    // ツールバーの高さ
    toolbar: {
      minHeight: 64,
    },
  },
  // 各パーツのスタイルをカスタマイズ
  props: {
    MuiCheckbox: {
      color: 'primary',
    },
    MuiList: {
      dense: true,
    },
    MuiTable: {
      size: 'small',
    },
    MuiTextField: {
      variant: 'outlined',
    },
  },
});

export default theme;

マテリアルデザイン仕様のカラーは『こちら』で確認できます。

テーマをコンポーネントに適用

以下の例は create-react-app で作成されたindex.jsに適用しています。
ポイントはMuiThemeProviderをimportしてコンポーネントに適用してあげることです。
パラメーターに先ほど作成したtheme.jsを渡してあげてください。

index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
// カスタムしたテーマ(スタイル)を定義
import { MuiThemeProvider } from '@material-ui/core/styles';
import theme from './styles/theme';

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

reportWebVitals();

5
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
9