2

I have the following test code (following the guide in the Material UI typescript docs)

import * as React from 'react';

import { Theme } from '@material-ui/core/styles/createMuiTheme';
import { WithStyles } from '@material-ui/core';
import { createStyles } from '@material-ui/core/styles';
import Drawer from '@material-ui/core/Drawer';

const drawerWidth = 240;

const styles = (theme: Theme) => createStyles({
  root: {
    flexGrow: 1,
    height: 430,
    zIndex: 1,
    overflow: 'hidden',
    position: 'relative',
    display: 'flex',
  },
  appBar: {
    zIndex: theme.zIndex.drawer + 1,
  },
  drawerPaper: {
    position: 'relative',
    width: drawerWidth,
  },
  content: {
    flexGrow: 1,
    backgroundColor: theme.palette.background.default,
    padding: theme.spacing.unit * 3,
    minWidth: 0,
  },
  toolbar: theme.mixins.toolbar,
});

interface Props extends WithStyles<typeof styles> {}
interface State {}

export class Sidebar extends React.Component<Props, State> {
  render() {
    const { classes } = this.props;
    return (
      <Drawer
        style={{position: 'relative', width: drawerWidth}}
        variant='permanent'
        classes={{
          paper: classes.drawerPaper,
        }}
      >
        <div className={classes.toolbar} />
      </Drawer>
    );
  }
}

export default Sidebar;

Now, if I try using this component elsewhere by doing:

import * as React from 'react';

import Grid from '@material-ui/core/Grid';

import Sidebar from './Sidebar';


export class Main extends React.Component {
  public render() {
    return (
      <Grid container>
        <Grid container item xs={12}>
          <Sidebar />
        </Grid>
      </Grid>
    );
  }
}

export default Main;

I am given the error that classes is missing from within the Main component and cannot read property drawerPaper of undefined within the SideBar component. I assumed the extend WithStyles<typeof styles> would resolve that issue but it still doesn't help when trying to import and use the SideBarcomponent. I have very little experience with Material UI theming so any guidance would be immensely appreciated.

1 Answer 1

4

You haven't attached your styles to the component. There is no connection in your code between the styles that you created and the rest of the code.

To do it you need to use HOC withStyles. Instead of export default Sidebar; just do export default withStyles(styles)(Sidebar);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.