【React】Material UI(MUI)のテーマを変更してカスタマイズする方法|ポートフォリオサイトの作り方

作成日: 更新日:

開発環境

  • Visual Studio Code:version 1.73.0
  • OS:Windows10
  • Node.js:v18.14.0
  • npm:9.3.1
  • react:18.2.0
  • react-dom:18.2.0
  • react-router-dom:6.8.2
  • typescript:4.9.5
  • mui:5.11.10
  • mui/icons-material:5.11.11
  • chart.js:4.4.0
  • react-chartjs-2:5.2.0
  • axios:1.5.0
  • cors:2.8.5
  • express:4.18.2
  • nodemailer:6.9.5

ReactでMaterial UI(MUI)のテーマを変更してカスタマイズする手順

ReactでMaterial UI(MUI)のテーマを変更してカスタマイズする手順を解説します。

テーマコンポーネントを作成する

まずは「react-portfolio-app/src/themes/配下」に「Theme.tsx」を作成します。

1// src\themes\Theme.tsx
2import { createTheme } from '@mui/material/styles';
3
4const theme = createTheme({
5    palette: {
6        primary: {
7            main: '#ff5722',
8        },
9        secondary: {
10            main: '#f50057',
11        },
12    },
13    typography: {
14        fontFamily: 'Arial, sans-serif',
15        fontSize: 14,
16        fontWeightLight: 300,
17        fontWeightRegular: 400,
18        fontWeightMedium: 700,
19
20        h1: { fontSize: 60 },
21        h2: { fontSize: 48 },
22        h3: { fontSize: 42 },
23        h4: { fontSize: 36 },
24        h5: { fontSize: 20 },
25        h6: { fontSize: 18 },
26        subtitle1: { fontSize: 18 },
27        subtitle2: { fontSize: 18 },
28        body1: { fontSize: 16 },
29        body2: { fontSize: 16 },
30        button: { textTransform: 'none' },
31    },
32});
33
34export default theme;

Material UIの公式サイトでテーマオプションのサンプルがあります。 公式サイト:https://mui.com/material-ui/customization/theming/ 今回はテーマカラーを変更したいので「palette」プロパティの「primary」「secondary」のカラーコードをしています。 また、ポートフォリオサイトで使用するフォントを全体的に整えたいため、「typography」プロパティにフォントサイズやフォントの太さ、フォントサイズをカスタマイズしています。

インデックスコンポーネントにテーマを読み込ませる

次にインデックスコンポーネントにテーマを読み込ませていきます。

1// src\index.tsx
2
3import React from 'react';
4import ReactDOM from 'react-dom/client';
5import './index.css';
6import App from './App';
7import reportWebVitals from './reportWebVitals';
8import { BrowserRouter } from 'react-router-dom';
9
10+ import { ThemeProvider } from "@mui/material/styles";
11+ import Theme from "./themes/Theme";
12
13const root = ReactDOM.createRoot(
14  document.getElementById('root') as HTMLElement
15);
16root.render(
17  <React.StrictMode>
18+   <ThemeProvider theme={Theme}>
19      <BrowserRouter>
20        <App />
21      </BrowserRouter>
22+   </ThemeProvider>
23  </React.StrictMode>
24);
25
26// If you want to start measuring performance in your app, pass a function
27// to log results (for example: reportWebVitals(console.log))
28// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
29reportWebVitals();

最初に「ThemeProvider」と「Theme.tsx」をimportします。 次に「ThemeProvider」の引数に先ほど作成したテーマコンポーネントの「Theme」を渡すことにより、ポートフォリオサイト全体にカスタマイズしたテーマを適用することができます。

ほかにもコンポーネント単位のスタイルを割り当てることができる

こちらは余談になりますが、ほかにもコンポーネント単位のスタイルを割り当てることができます。

// src\pages\homes\top.tsx
import React from "react";
import Box from "@mui/material/Box";
import Container from "@mui/material/Container";
import Grid from "@mui/material/Grid";
import Typography from "@mui/material/Typography";
import Button from "@mui/material/Button";

import MV from "../../assets/images/mv.jpg"
import SkillList from "../../components/SkillList"
import ProductionList from "../../components/ProductionList"
import ProfileList from "../../components/ProfileList";
import ContactForm from "../../components/ContactForm";

+ const styles = {
+     boxContainer: {
+         display: 'flex',
+         flexDirection: 'column',
+         alignItems: 'center',
+         justifyContent: 'center',
+         margin: '60px 0',
+     },
+ };

const Top: React.FC = () => {
    return(
        <>
            <Box sx={{ height: "65vh", backgroundImage: "url(" + MV + ")", backgroundSize: "cover", backgroundPosition: "center", position: "relative" }}>
                <Container maxWidth='md' sx={{ position: "absolute", top: "30%", left: "50%", transform: "translateX(-50%) translateY(-50%)" }}>
                    <Grid container rowSpacing={2} columnSpacing={2} sx={{ textAlign: "center",color: "#FFFFFF", textShadow: "1px 1px 3px #000000" }}>
                        <Grid item xs={12} md={12}>
                            <Typography component="h2" variant="h2">
                                MVタイトル
                            </Typography>
                        </Grid>
                        <Grid item xs={12} md={12}>
                            <Typography>
                                テキストテキストテキストテキストテキストテキストテキストテキストテキストテキスト
                            </Typography>
                        </Grid>
                    </Grid>
                </Container>
                <Button variant="contained" size="large" sx={{ position: "absolute", bottom: "10%", left: "50%", transform: "translateX(-50%)" }}>
                    LearnMore
                </Button>
            </Box>
+           <Box sx={styles.boxContainer}>
                <Container maxWidth='md'>
                    <SkillList />
                </Container>
            </Box>
+           <Box sx={styles.boxContainer}>
                <Container maxWidth='md'>
                    <ProductionList />
                </Container>
            </Box>
+           <Box sx={styles.boxContainer}>
                <Container maxWidth='md'>
                    <ProfileList />
                </Container>
            </Box>
+           <Box sx={styles.boxContainer}>
                <Container maxWidth='md'>
                    <ContactForm />
                </Container>
            </Box>
        </>
    );
};

export default Top;

上記のようにスタイルを定義することにより、Material UI(MUI)のコンポーネントにスタイルを効率よく適用することができます。
こういった場合は「styles」というディレクトリを作成し、そこにスタイルコンポーネントを作成していけばコードの管理もしやすくなるかと思います。

## おわりに

ReactでMaterial UI(MUI)のテーマをカスタマイズする方法について解説していきましたが、いかがだったでしょうか。
テーマの変更はそんなに難しいわけでもないため、サイト全体の印象を整えられるようにテーマコンポーネントを適用しておくとデザインの効率化にもなります。
是非、ReactでMaterial UI(MUI)のテーマを使いこなして、おしゃれなデザインにしていきましょう。
【React】Material UI(MUI)のテーマを変更してカスタマイズする方法|ポートフォリオサイトの作り方 | いっしー@Webエンジニア