Created
October 9, 2018 13:45
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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
commented
Nov 25, 2020
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment