When using Material UI Typography component sometimes we want to add new custom variants with custom styling or change the default styling of the variants already defined by MUI
We are going to add a new typography variant to the ones already defined by MUI, for this we are going to create a theme and add our new variant, we can also change the css rules for the ones already defined by MUI
// ./theme.tsx here we are going to define our new typographies and change the css rules from the ones already defined by MUI
import React from "react";
import { ThemeProvider, createTheme } from "@mui/material/styles";
import { TypographyOptions } from "@mui/material/styles/createTypography";
// Add new custom typography variants to the ones already defined by MUI
declare module "@mui/material/Typography" {
interface TypographyPropsVariantOverrides {
customBody1: true;
}
}
// Interface defining new typography variants
interface ExtendedTypographyOptions extends TypographyOptions {
customBody1: React.CSSProperties;
}
// Base theme
export const baseTheme = createTheme({
typography: {
// Change font family of all typographies
fontFamily: [
"Nunito",
"Roboto",
'"Helvetica Neue"',
"Arial",
"sans-serif",
].join(","),
// Change default h1 css rules
h1: {
fontWeight: 600,
},
// Change default h2 css rules
h2: {
color: "blue",
fontSize: "1.5rem",
fontWeight: "600",
},
// Add custom customBody1 typography with css rules
customBody1: {
color: "red",
fontSize: "1rem",
fontWeight: 600,
},
} as ExtendedTypographyOptions,
});
export const Theme = ({ children }: { children: JSX.Element }) => {
return <ThemeProvider theme={baseTheme}>{children}</ThemeProvider>;
};
This is an example of how to use our new variant
// ./index.tsx
import React from "react";
import ReactDOM from "react-dom";
import { Theme } from "./theme";
import { Typography } from "@mui/material";
function App() {
return (
<Theme>
<>
<Typography variant="h2">H2 Typography</Typography>
<br />
<Typography variant="customBody1">customBody1 Typography</Typography>
</>
</Theme>
);
}
ReactDOM.render(<App />, document.querySelector("#app"));
You can find a CodeSandbox with the implementation on the following link https://codesandbox.io/p/sandbox/l3n65c