H4rd_B4se
H4rd_B4se

Reputation: 91

ReactJS Material UI withStyles incl. theme in TS

I tried to convert the Material UI Dashboard into TypeScript. https://github.com/mui-org/material-ui/blob/master/docs/src/pages/page-layout-examples/dashboard/Dashboard.js

Currently I'm facing the problem that the CSS style definitions cannot be set on withStyles function when exporting the Dashboard.

const styles = (theme: Theme) => ({
  root: {
    display: 'flex',
  },
  toolbar: {
    paddingRight: 24, // keep right padding when drawer closed
  },
  toolbarIcon: {
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'flex-end',
    padding: '0 8px',
    ...theme.mixins.toolbar,
  },
  appBar: {
    zIndex: theme.zIndex.drawer + 1,
    transition: theme.transitions.create(['width', 'margin'], {
      easing: theme.transitions.easing.sharp,
      duration: theme.transitions.duration.leavingScreen,
    }),
  },
  .....
});

If I correctly understand, I need this theme reference to adjust the style to the current Theme. But how do I get the current theme when calling the style function?

export default withStyles(styles(/*WHAT TO PUT IN HERE?*/))(Dashboard);

Upvotes: 4

Views: 8122

Answers (2)

Shakeel Haider
Shakeel Haider

Reputation: 137

Import withStyle from material-ui and just use it as it is:

const style = withStyle((theme) => ({
    root: {
    display: 'flex',
    },
    toolbar: {
    paddingRight: 24, // keep right padding when drawer closed
    },
    toolbarIcon: {
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'flex-end',
    padding: '0 8px',
    ...theme.mixins.toolbar,
    },
    appBar: {
    zIndex: theme.zIndex.drawer + 1,
    transition: theme.transitions.create(['width', 'margin'], {
      easing: theme.transitions.easing.sharp,
      duration: theme.transitions.duration.leavingScreen,
    }),
  },
}));

Upvotes: 2

Sebastian
Sebastian

Reputation: 3594

export default withStyles(styles)(Dashboard);

withStyles will determine if it needs to call it with the theme or not.

withTheme or withStyles(stylesObjectOrCreator, { withTheme: true }) is only required if you need to access the theme inside your component via props.

API: https://material-ui.com/customization/css-in-js/#withstyles-styles---options----higher-order-component

Upvotes: 6

Related Questions