Theming guide in React with Material-UI (and styled-components)
I wanted to create this post for a long time to help anyone in need of a theming guide for Material-UI components (library) in React. I will try to guide you with step by step details.
In case you need to know more about Material-UI library please follow the below link.
Let’s start with a detailed step by step process by creating our project.
npx create-react-app my-project
The next step is to add Material-UI to our project. (If you want to use styled-components along with material-ui you can add it to our project).
You can ignore styled-components if you just decide to go with material-ui.
npm install @material-ui/core styled-components
or
yarn add @material-ui/core styled-components
Create a new theme folder under src directory. And add myTheme.js file with the following content.
Next create a ThemeWrapper.js file under theme directory, and copy the following code. This will create a wrapper for our app and will apply custom theme we just created. If you don’t want to use styled-components you can remove all the code related to styled-components and it will just work with material-ui.
Add an index.js file under theme directory and add the following exports.
Now wrap the return in App.js with our new wrapper. Our theme wrapper needs a mui theme object which we will provide in our App.js. Here we are using media query util provided by material-ui to know the system-wide theme (and our wrapper applies the theme — light vs dark based on this automatically). If you don’t want to use system-wide theme but want to implement your own light vs dark switch, you can do it and provide the value to myTheme.
Voila! That’s all you need to do. myTheme.js created above has a minimum set of theming props, but you can customize it to whatever extent you want your theme to be.
Let’s see it in action by running our code.
This is how our app should now look like when we run the code.
Now change your browser theme to dark (if using Mac change system theme to dark), and your page should automatically get the dark theme applied.
Let’s see how we can use our theme props with styled-components. We will have access to all theme props inside our styled function as we already wrapped styled-components theme provider in theme wrapper.
And this is how our new custom component looks in browser (both in light and dark themes with no additional code).
This wraps our discussion. Hope this will help kickstart your custom themes using material-ui and styled-components. And I just want to iterate that this is one of the many approaches to style your app and the one which I’m comfortable using and have used the same in many of my projects.