Saturday, June 8, 2019

Material UI - Theme provider

Lets say we create an app with

It seems that you will need a couple of material-ui components:

An AppBar
2 Buttons

And the app.js look like below

import AppBar from 'material-ui/AppBar';
import Button from 'material-ui/Button';
import React, { PureComponent } from 'react';

export default class Header extends PureComponent {
  render() {
    return (
     
       

         
           
Button 1

         
         
           
Button 2

         
       
     
    );
  }
}

To customise the material theme, below to be done

First, create a file theme.js in your app folder. We would like to give some pinkful color to our app bar:

import { createMuiTheme } from 'material-ui/styles';
import indigo from 'material-ui/colors/indigo';
import pink from 'material-ui/colors/pink';
import red from 'material-ui/colors/red';

export default createMuiTheme({
  palette: {
    primary: pink,
    secondary: indigo // Indigo is probably a good match with pink
  }
});

Then, we have to provide the theme above to your app. In order to this, we will encapsulate our app in a MuiThemeProvider.

import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import theme from 'xx/xx/theme';

Encapsulate the app in it and pass your theme file in props
export default class Header extends PureComponent {
  render() {
    return (
     
       
         

           
             
Button 1

           
           
             
Button 2

           
         
       
     
    );
  }
}

One step further, what if we want to customise all instances of a component type?

To customize a specific kind of material UI components within our app, we will add an overrides property to our theme.js file as described below. You will need to provide to your theme object, the name and class of the component you want to customize. This will be found in the material-ui API documentation.


import { createMuiTheme } from 'material-ui/styles';
import indigo from 'material-ui/colors/indigo';
import pink from 'material-ui/colors/pink';
import red from 'material-ui/colors/red';

export default createMuiTheme({
  palette: {
    primary: pink,
    secondary: indigo
  },
  overrides: {
    MuiButton: {
      root: {
        color: 'white',
        '&:hover': {
          backgroundColor: 'purple'
        }
      }
    }
  }
});

And what if we need to override for a specific instance of a component ?

MaterialUI theme will not be of any help here anymore, and our best chance is to inline style our left Button.

export default class Header extends PureComponent {
  render() {
    return (
     
       
         

           
             
Button 1

           
           
             
Button 2

           
         
       
     
    );
  }
}


https://blog.bam.tech/developper-news/get-the-best-of-your-react-app-design-by-using-material-ui-theme

No comments:

Post a Comment