Farah10
Farah10

Reputation: 91

Materials UI: Can't get useStyles to work in Class Component

I'm trying to access useStyles from my Class component, but I keep getting:

TypeError: Cannot read property 'root' of undefined

This is what Materials UI provides: useStyles:

const useStyles = makeStyles((theme) => ({
  root: {
    flexGrow: 1,
  },
  menuButton: {
    marginRight: theme.spacing(2),
  },
  title: {
    flexGrow: 1,
  },
}));


export default function ButtonAppBar() {
  const classes = useStyles();

  return (
    <div className={classes.root}>
      <AppBar position="static">
        <Toolbar>
          <IconButton edge="start" className={classes.menuButton} color="inherit" aria-label="menu">
            <MenuIcon />
          </IconButton>
          <Typography variant="h6" className={classes.title}>
            News
          </Typography>
          <Button color="inherit">Login</Button>
        </Toolbar>
      </AppBar>
    </div>
  );
}

In their example, they call useStyles() in their function. However that doesn't work with a class.

Based off of what I've come up with from researching, here's what I have:

const useStyles = makeStyles((theme) => ({
    root: {
      flexGrow: 1,
    },
    menuButton: {
      marginRight: theme.spacing(2),
    },
    title: {
      flexGrow: 1,
    },
  }));

export default class Navbar extends React.Component {
    render() {
        const {classes} = this.props;
        return(
            <div className={classes.root}>
      <AppBar position="static">
        <Toolbar>
          <IconButton edge="start" className={classes.menuButton} color="inherit" aria-label="menu">
            <MenuIcon />
          </IconButton>
          <Typography variant="h6" className={classes.title}>
            News
          </Typography>
          <Button color="inherit">Login</Button>
        </Toolbar>
      </AppBar>
    </div>
        )
    }
}

Upvotes: 0

Views: 151

Answers (1)

koralarts
koralarts

Reputation: 2112

Since makeStyles returns a hook, that you can call within your functional component. This method of creating classes doesn't work in Class components. Instead, you need to use withStyles -- a HOC that can be wrapped around your Class component.

Example:

class MyComponent extends React.Component {
  render() {
    const { classes } = this.props
    return (
      <div className={classes.container}>
        ...
      </div>
    )
  }
}
const ≈ = withStyles({
  container: { background: 'red' })
})(MyComponent)

export default ComponentWithClasses

https://material-ui.com/styles/advanced/#withstyles

Upvotes: 1

Related Questions