Skip to content

Instantly share code, notes, and snippets.

@jakewtaylor
Last active August 31, 2022 18:21
Show Gist options
  • Save jakewtaylor/8b80dc578bc37163e90c6ada48b1ffb2 to your computer and use it in GitHub Desktop.
Save jakewtaylor/8b80dc578bc37163e90c6ada48b1ffb2 to your computer and use it in GitHub Desktop.
useStyles() React Hook
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',
},
};
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