4
votes

My question is very simple, I want to use the Material-ui default darkTheme in a part of my app. Here is a sample of code :

<div>
  <MuiThemeProvider muiTheme={getMuiTheme(darkBaseTheme)}>
    <div>
      <AppBar title="I am dark" />
      <MyCustomComponent label="I should be dark but I am not" />
    </div>
  </MuiThemeProvider>
  <MuiThemeProvider muiTheme={getMuiTheme(lightBaseTheme)}>
      <p>I am in the lightBaseTheme (default theme)</p>
  </MuiThemeProvider>
</div>

The first part of the app must be in the dark theme (that's a left menu), the second part in the light theme (that's the app itself).

The AppBar that is a direct child of the MuiThemeProvider is indeed dark, however, MyCustomComponent and its children (even when they are base Material-ui components such as RaisedButton) are not using the dark theme.

What is the simplest way to have MyCustomComponents and all its sub-children to use the dark theme too ?

2

2 Answers

2
votes

You need to wrap all inside MuiThemeProvider into one element.

<MuiThemeProvider muiTheme={getMuiTheme(darkBaseTheme)}>
  <div>
    <AppBar title="I am dark" />
    <MyCustomComponent label="I should be dark but I am not" />
  </div>
</MuiThemeProvider>

actually you had to have an error like

MuiThemeProvider.render(): A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.

Of course only Material-UI components inside your MyCustomComponent will have themed appearance. Everything else you need to make manually: in a way shown by Jeff McCloud or by using context like this:

function MyCustomComponent (props, context) {
    const { palette } = context.muiTheme;
    // Now you have access to theme settings. for example: palette.canvasColor
}

MyCustomComponent.contextTypes = {
    muiTheme: React.PropTypes.object.isRequired,
};

One more way to stylize plain HTML or React Components is to wrap them into react-theme-provider. Like this:

import ThemeProvider from 'react-theme-provider';

<MuiThemeProvider muiTheme={getMuiTheme(darkBaseTheme)}>
  <div>
    <AppBar title="I am dark" />
    <ThemeProvider>
      <MyCustomComponent label="I should be dark and I am!" />
    </ThemeProvider>
  </div>
</MuiThemeProvider>

reference: https://github.com/callemall/material-ui/blob/master/src/styles/MuiThemeProvider.js#L7

1
votes

You need to designate that your custom component is "themeable". You do this by wrapping your component in the 'muiThemeable' Higher-Order Component:

import React from 'react';
import muiThemeable from 'material-ui/styles/muiThemeable';

class MyCustomComponent extends React.Component {
// ... your component will now have access to "this.props.muiTheme"
}


export default muiThemeable()(MyCustomComponent);

reference: http://www.material-ui.com/#/customization/themes