Thursday, August 15, 2019

ReactJs / Angular - Override Material UI Theme

Hello,

While working with React or Angular Applications we normally uses Material UI themes and components and it's great choice because it has nice set of themes and colors and ready to use components. That makes our life easy.

One challenge we face is, in case if we want to change or override the theme. For example Material ui has dark blue theme. What if you want to change colors or dark blue theme with your own color. One option is you can declare the class with same name and give your own property. However the better solution is to use theme override. In this blog I am going to mention how to this.

Please note the method I am going to mention here is specific to React application.

First of all create theme.js file in your app and add following code to it.

import React from "react";
import { MuiThemeProvider, createMuiTheme } from "@material-ui/core/styles";
import CssBaseline from "@material-ui/core/CssBaseline";
import blueGrey from "@material-ui/core/colors/blueGrey";
import lightBlue from "@material-ui/core/colors/lightBlue";
import "typeface-roboto";

import { ThemeProvider as ScThemeProvider } from "styled-components";

export default props => (
  <ScThemeProvider theme={muiTheme}>
    <MuiThemeProvider theme={muiTheme}>
      <CssBaseline>{props.children}</CssBaseline>
    </MuiThemeProvider>
  </ScThemeProvider>
);

const theme = {
  overrides: {
  },
  palette: {
    primary: { 
      main: '#MAIN_COLOR' 
    }, 
    secondary: { 
      main: '#SECONDARY_COLOR' 
    },
    background: {
      default: '#BACKGROUND_COLOR'
    }
  },
  type: "dark"
};

const muiTheme = createMuiTheme(theme);

Now here in overrides you can add code to override. For example if you want to change panel header. If you inspect html element you will find it has a class MuiPaper-root

Here is how you can override base CSS of it.

   overrides: {
    MuiPaper: {
      root: {
        background: '#YOUR_COLOR'
      },
      rounded: {
        background: '#YOUR_COLOR'
      }
    }

Same way for any other components you can do it. Inspect the HTML structure, find out Class Name and override it.

No comments:

Post a Comment