I am using React with Material UI and am refactoring one of my components now. My original component looks something like this:
// All the import statements here
const styles = theme => ({
container: {
margin: 'auto',
maxWidth: '1200px',
background: theme.palette.primary.main
// More styles here
},
});
const Component = ({ classes }) => (
<div>
<div className={classes.container}>
{/* Some content */}
</div>
<div className={classes.container}>
{/* Some content */}
</div>
</div>
);
export default withStyles(styles)(Component);
But after refactoring the component I need to access the 'container' class in two different components. The only approach I could come up with was creating a new file in my root called sharedStyles.js, which I then import in both of those components and extend its style object like this:
File: sharedStyles.js
export default theme => ({
container: {
margin: 'auto',
maxWidth: '1200px',
background: theme.palette.primary.main
// Some more styles
},
});
File: NewComponent.js
// All the import statements here - including the sharedStyles.js
const styles = theme => ({
...sharedStyles(theme),
// Some more styles
});
const NewComponent = ({ classes }) => (
<div className={classes.container}>
{/* Some content */}
</div>
);
export default withStyles(styles)(NewComponent);
File: RefactoredComponent.js
// All the import statements here - including the sharedStyles.js
// and NewComponent.js
const styles = theme => ({
...sharedStyles(theme),
// Some more styles
});
const RefactoredComponent = ({ classes }) => (
<div>
<NewComponent />
<div className={classes.container}>
{/* Some content */}
</div>
</div>
);
export default withStyles(styles)(RefactoredComponent);
Even though this approach works, I don't really like it. So my question is: Is there a better way how to share one JSS class across multiple components located in multiple files?.