I am trying to have different parts of my application have different fonts. I want to achieve this through theme nesting: https://mui.com/styles/advanced/#theme-nesting.
But theme nesting doesn't work when overriding fonts.
App.js:
import React from "react";
import { ThemeProvider, Button, Typography } from "@mui/material";
import outerTheme from "./outerTheme";
import innerTheme from "./innerTheme";
const App = () => {
return (
<ThemeProvider theme={outerTheme}>
<Button>outer</Button>
<Typography color="primary">outer</Typography>
<ThemeProvider theme={innerTheme}>
<Button>inner</Button>
<Typography color="primary">inner</Typography>
</ThemeProvider>
</ThemeProvider>
);
};
export default App;
outerTheme.js:
import { createTheme } from "@mui/material";
const outerTheme = createTheme({
palette: {
primary: {
main: "#ff0000",
},
},
typography: {
fontFamily: "sans-serif",
},
});
export default outerTheme;
innerTheme.js:
import { createTheme } from "@mui/material";
import outerTheme from "./outerTheme";
const innerTheme = createTheme(outerTheme, {
palette: {
primary: {
main: "#0000ff",
},
},
typography: {
fontFamily: "serif",
},
});
export default innerTheme;
The result shows that all buttons and typographies use the outer theme's font (i.e. sans-serif) but use the correct respective theme colors.
The nested theme works, it's just that your fontFamily is never set in the first place. If you want to override the Button's font family, you need to set the value in typography.button.fontFamily, not typography.fontFamily (Source):
const outerTheme = createTheme({
typography: {
button: {
fontFamily: 'sans-serif',
},
},
});
const innerTheme = createTheme(outerTheme, {
typography: {
button: {
fontFamily: 'serif',
},
},
});
EDIT: To override the fontFamily of all MUI components, you need to update all variants:
function createFontFamily(fontFamily) {
return {
h1: { fontFamily },
h2: { fontFamily },
h3: { fontFamily },
h4: { fontFamily },
h5: { fontFamily },
h6: { fontFamily },
subtitle1: { fontFamily },
subtitle2: { fontFamily },
body1: { fontFamily },
body2: { fontFamily },
button: { fontFamily },
caption: { fontFamily },
overline: { fontFamily },
};
}
const outerTheme = createTheme({
typography: createFontFamily('sans-serif'),
});
const innerTheme = createTheme(outerTheme, {
typography: createFontFamily('serif'),
});