Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Material-UI React: Global theme override for Paper component

I have a React app built with the latest Material-UI component library.

I use many instances of the Paper component. I want to apply margins and padding to all them at once, without manually repeating this process for every instance.

I looked up the Material-UI documentation on the topic, and from what I can tell, the following code should correctly override how Paper looks:

const theme = createMuiTheme({
    overrides: {
        Paper: {
            root: {
                padding: '10px',
                marginBottom: '10px',
            },
        },
    },
});

Below is where overridden style should apply:

<ThemeProvider theme={theme}>
    {/* ... */}
    <Paper>
        Content goes here
    </Paper>
    {/* ... */}
</ThemeProvider>

But the overridden values aren't being applied. Any suggestions as to what's going on?

Thanks!

like image 796
Andrei Avatar asked Dec 23 '18 19:12

Andrei


2 Answers

in your App.js add (please note MuiPaper and not Paper):

const theme = createMuiTheme({
  overrides: {
    MuiPaper: {
      root: {
        padding: '10px',
        marginBottom: '10px'
      },
    },
  }
});

at the same App.js file, wrap your HTML:

class App extends Component {
  render() {
    return (
      <MuiThemeProvider theme={theme}>
        <div className="App">
          <YourComponent1 />      
          <YourComponent2 />
          ...
        </div>
      </MuiThemeProvider>
    );
  }
}

this way, any Paper component rendered by React will have your CSS.

BTW, I created MUI schematics module which adds Material UI support, generates several Material UI components automatically and adds general theme rules in App.js. You are welcome to take a look / try it...

like image 119
Andriy Avatar answered Sep 27 '22 22:09

Andriy


You can also use your CssBaseline component if you're already using it for global reset...all depends on how you're structuring your theme.

Eg below is from the Mui docs: <CssBaseline.js>

const theme = createMuiTheme({
  overrides: {
    MuiCssBaseline: {
      '@global': {
        html: {
          WebkitFontSmoothing: 'auto',
        },
      },
    },
  },
});
      

 // ...
return (
  <ThemeProvider theme={theme}>
    <CssBaseline />
    {children}
  </ThemeProvider>
);

You can get more details from the docs here using CssBaseline to inject global theme overrides.

like image 34
Michael Mallette Avatar answered Sep 27 '22 22:09

Michael Mallette