2020-06-25
How to create a custom Material UI theme for Gatsby
material-ui, theme, gatsby, react, selfnote
material-ui, theme, gatsby, react, selfnote
** Note on 2020-06-26 **
There is a very nice customization video, React Material-UI Themes: Customize Material Components for your Project.
Been searching for easy way to customize Material UI (MUI hereafter) theme and found few online tools to help me get it done quick.
Most of steps here are for configuring Gatsby for Material UI theme but a custom MUI theme set up is easy.
npx gatsby new site-name-here
1npm install @material-ui/core2# or3yarn add @material-ui/core
1npm install -D gatsby-plugin-material-ui2# or3yarn add -D gatsby-plugin-material-ui
I will create a local plugin to keep the code organized.
Refer to Creating a Local Plugin for more info
Create a new local Gatsby plugins folder, ./plugins/custom-mui-theme in the project root
Configure Gatsby plugin
wrapRootElement.js
1import React from "react";2import { ThemeProvider } from "@material-ui/core/styles";3
4import theme from "./theme";5
6export const wrapRootElement = ({ element }) => {7 console.info(`theme`, theme);8 return <ThemeProvider theme={theme}>{element}</ThemeProvider>;9};
gatsby-browser.js
export { wrapRootElement } from "./wrapRootElement";
gatsby-ssr.js
export { wrapRootElement } from "./wrapRootElement";
package.json - Required for the local plugin
1{2 "name": "custom-mui-theme"3}
Create a new folder ./plugins/custom-mui-theme/theme
Create two files under the theme folder
theme.json
index.js
1import { createMuiTheme } from "@material-ui/core/styles";2import themeData from "./theme.json";3
4const themeName = "My custom theme name";5export default createMuiTheme({ ...themeData, themeName });
Configure gatsby-plugin-material-ui and add the custom-mui-theme (the latter should be below) in the project root's gatsby-config.js
1module.exports = {2 // ...3 plugins: [4 // other plugins ...5 {6 resolve: `gatsby-plugin-material-ui`,7 options: {8 stylesProvider: {9 injectFirst: true,10 },11 },12 },13 `custom-mui-theme`,14 ],15};
In ./src/pages/index.js, add the primary button to see if the color matches that of your custom style
1import React from "react";2
3import Button from "@material-ui/core/Button";4
5const IndexPage = () => (6 <>7 <Button color="primary" variant="contained">8 A button!9 </Button>10 <Button color="secondary" variant="contained">11 A button!12 </Button>13 </>14);15
16export default IndexPage;
You will see that the primary and secondary colors are applied according to the custom theme.
From here on, simply updating ./plugins/custom-mui-theme/theme/theme.json should update the MUI theme