Creating styles from Material-UI theme that can be reused across components?

0

Issue

In Material-UI 4, one can easily create styles that can be used inside a component. I use the makeStyles() function for this.

const useStyles = makeStyles((theme: Theme) => ({
    hoverableContent: {
        color: theme.palette.primary.contrastText,
        backgroundColor: theme.palette.primary.main,
        '&:hover': {
            backgroundColor: theme.palette.primary.dark
        }
    }
}));

const MyComponent = () => {
    const classes = useStyles();
    ...
}

However, I would like to reuse this style in multiple components. What is the best way to do this in Material-Ui 4?

Note: I think of this as a slightly higher level abstraction: sharing abstract classes (in a controlled way) instead of just colors (in a theme).

Solution

You could do one of the following:

  1. Share the style between your components
const styles = (theme: Theme) => ({
    hoverableContent: {
        color: theme.palette.primary.contrastText,
        backgroundColor: theme.palette.primary.main,
        '&:hover': {
            backgroundColor: theme.palette.primary.dark
        }
    }
})

This approach then leads to this question. How do you merge multiple styles? https://github.com/mui-org/material-ui/issues/11517

  1. Generate a global class name and apply it where it makes sense. But be careful with class name conflict and tree-shaking

Answered By – Olivier Tassinari

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More