Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reusing custom styles in material-ui

New to material-ui here and trying to work out the best way of using the css in js. I can see from the demo code that inserting styles as classes is pretty easy using 'withStyles' but if I do the following I'd need to re-create the 'grow' and 'defaultPadding' styles in every component.

import React from 'react';
import { withStyles } from '@material-ui/core/styles';
import Paper from '@material-ui/core/Paper';


function Dashboard(props) {

    const { classes } = props;

    return (

        <Paper className={classes.defaultPadding}>
            Hello
        </Paper>
    );

}

const styles = theme => ({
    grow: {
        flexGrow: 1
    },
    defaultPadding: {
        padding: theme.spacing.unit * 3 + 'px'
    }
});


export default withStyles(styles)(Dashboard);

I could easily create a factory method in an external file that returns a massive object containing all my default styles but I'd need to be able to pass the existing theme to it if I want to use things like 'theme.spacing.unit'.

So, is there a way to create a bunch of re-usable styles of my own, using theme values, then import them into any component?

Bonus question: Is it possible to create nested objects so I can do things like this? ...

className={classes.layout.header}
like image 577
jonhobbs Avatar asked Dec 02 '18 20:12

jonhobbs


1 Answers

I think creating an external factory method would work or you could also create a ThemeProvider to pass your theme to every component that needs the same styles.

In the Codesandbox I created two Dashboard components. One with styled-components just to show how a ThemeProvider works and the other component is using withStyles.

For withStyles factory I called it sharedStyles in the demo and with this you can create a new style object inside your components by calling it and spreading it to a new style (just if you need to add more styles).

Nesting inside styles seems not supported. You could create keys like layout.heading or flatten the object before using it (see code in the demo). Both not perfect and I wouldn't use it.

I'm personally prefering styled-components but you don't need to switch to it. You can look at the source code how they implemented it and use it in your code to pass the theme to your component.

The ThemeProvider is using React Context-Api.

like image 109
AWolf Avatar answered Nov 07 '22 00:11

AWolf