Eric Burel Eric Burel - 1 month ago 27
React JSX Question

Material-ui : darkTheme does not affect wrapped children

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 ?

Answer

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,
};

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