Skip to content

Instantly share code, notes, and snippets.

@terrysahaidak
Created December 20, 2019 20:52
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save terrysahaidak/892d7c8e0faafd40cd4ab04db903a0ca to your computer and use it in GitHub Desktop.
Save terrysahaidak/892d7c8e0faafd40cd4ab04db903a0ca to your computer and use it in GitHub Desktop.
Smallest styled components
function useStyles(styles) {
const [, forceUpdate] = useState();
const [width, height] = useDimensions();
useEffect(() => {
// TODO: debounce it
forceUpdate((v) => v + 1);
}, [width, height]);
return Object.entires(styles).reduce((acc, [key, value]) => {
if (typeof value === 'string' && value.includes('vh')) {
acc[key] = +value.split('vh')[0] * height;
} else if (typeof value === 'string' && value.includes('vw')) {
acc[key] = +value.split('vw')[0] * width;
} else {
acc[key] = value;
}
return acc;
}, {});
}
function createStyled(Kind) {
return (styles) => {
return ({ style, ...props }) => {
const parsedStyles = useStyles(styles);
return <Kind style={[parsedStyles, style]} {...props} />;
};
}
}
const styled = {
Text: createStyled(Text),
};
// example
const Container = styled.Text({
fontSize: '12vh',
});
@brmk
Copy link

brmk commented Dec 20, 2019

looks awesome!

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