How to style components using makeStyles and still have lifecycle methods in Material UI?

Sometimes, we want to style components using makeStyles and still have lifecycle methods in Material UI.

In this article, we’ll look at how to style components using makeStyles and still have lifecycle methods in Material UI.

How to style components using makeStyles and still have lifecycle methods in Material UI?

To style components using makeStyles and still have lifecycle methods in Material UI, we should use the withStyles higher order component.

For instance, we write:

import React from "react";
import { withStyles } from "@material-ui/styles";
import Button from "@material-ui/core/Button";

const styles = (theme) => ({
  root: {
    background: "linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)",
    border: 0,
    borderRadius: 3,
    boxShadow: "0 3px 5px 2px rgba(255, 105, 135, .3)",
    color: "white",
    height: 48,
    padding: "0 30px"
  }
});

class SpecialButton extends React.Component {
  render() {
    const { classes } = this.props;
    return <Button className={classes.root}>hello world</Button>;
  }
}

const StyledButton = withStyles(styles)(SpecialButton);

export default function App() {
  return <StyledButton />;
}

We create the styles function that returns an object with the styles we want to apply when we apply the classes.root class.

Next, we create the SpecialButton component that takes the classes prop that’s injected with the withStyles higher-order component and the styles function.

And then we set className of the button to classes.root to set the class attribute of the button to root.

Finally, we rendered the StyledButton that’s created with withStyles in App.

As a result, we should see a button with gradients on the screen.

Conclusion

To style components using makeStyles and still have lifecycle methods in Material UI, we should use the withStyles higher order component.