Skip to content
Advertisement

Is there a non-hook alternative for the React Material-UI makeStyles() function that works for class Components

Im using the makeStyles() function in material-UI’s react library, and am getting the following error

Hooks can only be called inside the body of a function component.

Below is an example of the kind of code I am using.

const useStyles = makeStyles(theme => ({
  container: {
    display: 'flex',
    flexWrap: 'wrap',
  },
  textField: {
    marginLeft: theme.spacing(1),
    marginRight: theme.spacing(1),
  },
  dense: {
    marginTop: theme.spacing(2),
  },
  menu: {
    width: 200,
  },
}));

class Demo extends Component {
  constructor(props) {
    super(props);
  }
  render() {
    const classes = useStyles();
    return (
      <TextField
        className={classes.textField}
      >
        <MenuItem>Demo</MenuItem>
      </TextField>
    )
  }
}

I know the error is being thrown because I’m trying to use makeStyles() in my class component (As shown above).

However, I’m curious if there is an alternative to makeStyles() for class components in Material-UI’s react library, or what the syntax would be to get the functionality of make-styles in a class component.

Advertisement

Answer

makeStyles is just a high order function (returns a hook) to apply styles in functional components. You can always use withStyles, which is an HOC for the exact same purpose and works for both class an functional components

import { withStyles } from '@material-ui/styles'

const styles = {
   root: {
     background: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)'
   }
};

class Component extends React.Component{
    render(){
        const { classes } = this.props
        return <div className={classes.foo} />
    }
}
export default withStyles(styles)(Component)
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement