Skip to content

Instantly share code, notes, and snippets.

@dlochrie
Created October 9, 2018 13:45
Show Gist options
  • Save dlochrie/8e962277e0b8da3bca8c5db72e5d95c2 to your computer and use it in GitHub Desktop.
Save dlochrie/8e962277e0b8da3bca8c5db72e5d95c2 to your computer and use it in GitHub Desktop.
Utility that combines and merges multiple Material UI styles into on function for usage with the "withStyles" HOC.
/**
* Combines/merges Material UI styles so that they may be used on a single
* component with the "withStyles" HOC.
*
* @see {@link https://github.com/mui-org/material-ui/issues/11517#issuecomment-407509327}
* @see {@link https://material-ui.com/customization/css-in-js/}
*
* Usage:
*
* import { combineStyles } from '/path/to/thisFile';
*
* import { style1 } from '/path/to/style1';
* import { style2 } from '/path/to/style1';
*
* const style3 = theme => ({
* toolbar: {
* backgroundColor: theme.palette.primary.main,
* color: '#fff',
* ...theme.mixins.toolbar,
* }
* });
*
* const combinedStyles = combineStyles(style1, style2, style3);
*
* export default withStyles(combinedStyles)(MyComponent);
*
* @param {...Object|Function} styles The objects and functions that should be
* merged.
* @return {!Function} The merged styles function to pass to "withStyles".
*/
function combineStyles(...styles) {
return function CombineStyles(theme) {
const outStyles = styles.map((arg) => {
// Apply the "theme" object for style functions.
if (typeof arg === 'function') {
return arg(theme);
}
// Objects need no change.
return arg;
});
return outStyles.reduce((acc, val) => Object.assign(acc, val));
};
}
export default combineStyles;
@karaoak
Copy link

karaoak commented Nov 25, 2020

import { Theme } from '@material-ui/core';
import _merge from 'lodash.merge';

export const combineStyles = (...styles: unknown[]) => (theme: Theme) =>
  styles.reduce((acc, val) => _merge(acc, typeof val === 'function' ? val(theme) : val), {});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment