user3836484
user3836484

Reputation: 205

Extracting styles in React + material-ui

I am using React + material-ui. I would like to extract the styles defined in each component into a common file.

if the followings are put in a single file, every works well:-

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

const styles = theme => ({
    createButton: {
        [theme.breakpoints.up('md')]: {
            borderRadius: '10px',
            display: 'block',
            margin: '0 auto',
            marginTop: '10px',
            marginBottom: '10px',
            width: '360px',
        },
        [theme.breakpoints.down('sm')]: {
            borderRadius: '0px',
            bottom: '0px',
            position: 'relative',
            width: '100%',
            height: '60px',
            fontSize: '20px',
        },
        backgroundColor: theme.palette.secondary.main,
        color: 'white',
        '&:hover': {
            backgroundColor: theme.palette.secondary.main,
        },
    }
});
...

class Home extends Component {
...
<Button className={this.props.classes.createButton}>Hello</Button>
...
}

export default (withStyles(styles)(Home));

now, I wish to extract the following into another file, e.g. common.js, then in future, I can import it in other components so that I can reuse the style:-

const styles = theme => ({
    createButton: {
        [theme.breakpoints.up('md')]: {
            borderRadius: '10px',
            display: 'block',
            margin: '0 auto',
            marginTop: '10px',
            marginBottom: '10px',
            width: '360px',
        },
        [theme.breakpoints.down('sm')]: {
            borderRadius: '0px',
            bottom: '0px',
            position: 'relative',
            width: '100%',
            height: '60px',
            fontSize: '20px',
        },
        backgroundColor: theme.palette.secondary.main,
        color: 'white',
        '&:hover': {
            backgroundColor: theme.palette.secondary.main,
        },
    }
});

then, when I

import { styles } from './somewhere/common';

the createButton style is not working anymore.

it mentioned

Attempted import error: 'styles' is not exported from './somewhere/common'.

Upvotes: 0

Views: 1270

Answers (1)

Oscar
Oscar

Reputation: 1238

You need to export styles from './somewhere/common', add this to the end of the file:

export default styles;

And import it using:

import styles from './somewhere/common'

Upvotes: 1

Related Questions