Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

material-ui-next - Dynamically set palette color

I am using "material-ui": "^1.0.0-beta.33" for my project. What I want to do is set primary palette color dynamically inside a react component (color will be fetched from some api). Basically I want to override below:

const theme = createMuiTheme({
  palette: {
    primary: "some color from api" 
  },
})

Is there a way to set this in componentDidMount function of any component?

Reference: https://material-ui-next.com/

like image 516
Ashish Agrawal Avatar asked Oct 17 '22 18:10

Ashish Agrawal


1 Answers

I created a component that uses MuiThemeProvider and wrap my entire app around that component. Below is the structure of the component.

import React, {Component} from "react";
import {connect} from "react-redux";
import {withStyles} from 'material-ui/styles';
import * as colors from 'material-ui/colors';
import { MuiThemeProvider, createMuiTheme } from 'material-ui/styles';
import { withRouter } from 'react-router-dom';

export class ThemeWrapperComponent extends Component {
  constructor(props){
    super(props);
  }

  render(){
    return (
      <MuiThemeProvider theme={createMuiTheme(
        {
          palette: {
            primary: { main: **colorFromApi** },
          }
      )}>
        <div>
            { this.props.children }
        </div>
      </MuiThemeProvider>
    )
  }
}

export const ThemeWrapper = withRouter(connect(mapStateToProps)(ThemeWrapperComponent));

Below is how I wrapped my app around this component:

 <ThemeWrapper>
    <div>          
      <Routes/>
    </div>                
 </ThemeWrapper>

Now, whatever colour you are sending from the api gets applied to the whole theme. More customisation can be done based on requirement.

like image 80
Ashish Agrawal Avatar answered Oct 21 '22 03:10

Ashish Agrawal