Cannot access pxToRem function in Material-ui for theme

Viewed 7830

I'm using material-ui with React. I'm trying to theme my application. Unfortunately the material-ui library provides a light-theme.js example (via some means), but the material-ui theming components rely on functions within the theme. Specifically the theme.typography.pxToRem function for calculating rem conversions.

How do I provide access to those functions on in my own theme?

Now, I would go through the steps of reimplementing pxToRem and similar on my theme, but it seems very unlikely that others have done that due to the nested closure used. What are others doing to access functions on the material-ui theme?

1 Answers

Material UI gives us access to override css classes by using createMuiTheme. You have to pass down theme to your app with MuiThemeProvider. Here is the way to implement it:

import { MuiThemeProvider, createMuiTheme } from '@material-ui/core/styles';

const fontSize = 14, // px
// Tell Material-UI what's the font-size on the html element.
// 16px is the default font-size used by browsers.
const htmlFontSize = 16,
const coef = fontSize / 14;

const theme = createMuiTheme({
  typography: {
    pxToRem: size => `${(size / htmlFontSize) * coef}rem`,
  },
});

in you render method:

 <MuiThemeProvider theme={theme}>
      <Component />
</MuiThemeProvider>

PS. I have tested it. it's working like a charm.

Please ask me any question regarding this. Happy to help

Related