Created
December 20, 2019 20:52
-
-
Save terrysahaidak/892d7c8e0faafd40cd4ab04db903a0ca to your computer and use it in GitHub Desktop.
Smallest styled components
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
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', | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
looks awesome!