Last active
August 31, 2022 18:21
-
-
Save jakewtaylor/8b80dc578bc37163e90c6ada48b1ffb2 to your computer and use it in GitHub Desktop.
useStyles() React Hook
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
import React from 'react'; | |
import { useStyles } from '../hooks/useStyles'; | |
export const Sidebar = ({ colourful = false }) => { | |
const styles = useStyles(stylesheet); | |
return ( | |
<div className={styles.sidebar}> | |
<p | |
className={styles.compose( | |
'sidebarText', | |
colourful && 'sidebarText_colourful', | |
)} | |
>Sidebar</p> | |
</div> | |
); | |
}; | |
const stylesheet = { | |
sidebar: { | |
background: 'red', | |
}, | |
sidebarText: { | |
fontSize: '1.5rem', | |
color: '#2c2c2c', | |
}, | |
sidebarText_colourful: { | |
color: '#ff0000', | |
}, | |
}; |
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
import { useMemo, useCallback } from 'react'; | |
import { StyleSheet, css } from 'aphrodite'; | |
import { theme } from '../shared/theme'; | |
export const useStyles = (stylesheet) => { | |
const styles = useMemo(() => { | |
if (typeof stylesheet === 'function') { | |
stylesheet = stylesheet(theme); | |
} | |
return StyleSheet.create(stylesheet); | |
}); | |
const getClass = useCallback((className) => { | |
if (Object.prototype.hasOwnProperty.call(styles, className)) { | |
return styles[className]; | |
} else { | |
throw new Error(`No CSS class '${className}' is defined!`); | |
} | |
}); | |
const composeClasses = useCallback((...classNames) => { | |
classNames = classNames.reduce((acc, className) => { | |
if (className) { | |
acc.push(getClass(className)); | |
} | |
return acc; | |
}, []); | |
return css(...classNames); | |
}); | |
const proxy = useMemo(() => new Proxy({}, { | |
get: function (_, className) { | |
if (className === 'compose') { | |
return composeClasses; | |
} | |
return css(getClass(className)); | |
}, | |
})); | |
return proxy; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment