この記事は?
Joy UI を使ってUIを構築する際、フォントやPrimary Color などの共通のスタイルを変更する方法についてです。
個別に変更するばは sx プロップスを使用すればいいのですが、全体の変更する場合は extendTheme を使います。
以下解説です。
よしなに。
環境
- React TS
- Joy UI v5.0.0-beta.49
- 2025.01.20 時点
やり方
以下のように thmes ディレクトリなどを作成し、その下にtheme.ts ファイルを作成します。
中身は例えば以下のようにしてみましょう。
extendTheme を使うのがポイントです。
// src/themes/theme.ts
import { extendTheme } from '@mui/joy/styles';
const theme = extendTheme({
colorSchemes: {
light: {
palette: {
primary: {
50: '#e3f2fd',
100: '#bbdefb',
200: '#90caf9',
300: '#64b5f6',
400: '#42a5f5',
500: '#2196f3',
600: '#1e88e5',
700: '#1976d2',
800: '#1565c0',
900: '#0d47a1',
},
},
},
},
fontFamily: {
display: 'Roboto, sans-serif',
body: 'Arial, sans-serif',
},
});
export default theme;
続いてこの関数を App.tsx で読み込みます。
CssVarsProvider で全てを囲ってあげます。そして、themeに先ほど作成したtheme.tsを渡してあげればスタイルが下層の全てのコンポーネントに適応されます。
import React from 'react';
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
import './styles/App.css';
import { RecoilRoot } from 'recoil';
// theme
import { CssVarsProvider } from '@mui/joy';
import theme from './themes/theme';
// component
// 省略
function App() {
return (
<RecoilRoot>
<CssVarsProvider theme={theme}>
<Router>
<Header />
<Analytics />
<Routes>
<Route path="/" element={<Top />} />
</Routes>
</Router>
</CssVarsProvider>
</RecoilRoot>
);
}
export default App;
たったこれだけで、プロジェクト全体に変更をかけられるようになりました!
お疲れ様です!!
参考
↓ 公式ドキュメント様
https://mui.com/joy-ui/customization/approaches
おまけ
mac, windows, 他OSでフォントを切り替えられるようにしてみました。
//
// このファイルは、JoyUI のテーマを定義するファイルです。
// created date: 2025.01.20
// created by: coiai
//
import { extendTheme } from '@mui/joy/styles';
// OSごとのフォント設定
const getSerifFont = () => {
const platform = navigator.platform.toLowerCase();
if (platform.includes('win')) {
return 'Yu Mincho, serif'; // Windows の場合は遊明朝
} else if (platform.includes('mac')) {
return 'Hiragino Mincho Pro, serif'; // Mac の場合はヒラギノ明朝
} else {
return 'serif'; // その他のOSはデフォルトのセリフ体
}
};
const theme = extendTheme({
colorSchemes: {
light: {
palette: {
primary: {
50: '#e3f2fd',
100: '#bbdefb',
200: '#90caf9',
300: '#64b5f6',
400: '#42a5f5',
500: '#2196f3',
600: '#1e88e5',
700: '#1976d2',
800: '#1565c0',
900: '#0d47a1',
},
},
},
},
fontFamily: {
display: getSerifFont(), // 見出し用フォント
body: getSerifFont(), // 本文用フォント
},
});
export default theme;

コメントを残す