Skip to content

Instantly share code, notes, and snippets.

@alex-cory
Last active December 5, 2019 00:56
Show Gist options
  • Save alex-cory/fb4e054713f8cebfaeba94bdae1d65ea to your computer and use it in GitHub Desktop.
Save alex-cory/fb4e054713f8cebfaeba94bdae1d65ea to your computer and use it in GitHub Desktop.
Converts a css string to a React js object using tagged template literal syntax
const css2obj = (strings, ...vals) => {
const css = strings.reduce((acc, str, i) => acc + str + (vals[i] || ''), '')
const r = /(?<=^|;)\s*([^:]+)\s*:\s*([^;]+)\s*/g, o = {}
css.replace(r, (m,p,v) => o[p.replace(/-(.)/g, (_,p) => p.toUpperCase())] = v)
return o
}
const actual = css2obj`
position: fixed;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
z-index: 1000;
`
const expected = {
position: 'fixed',
left: '50%',
top: '50%',
transform: 'translate(-50%,-50%)',
zIndex: 1000
}
_.isEqual(actual, expected) === true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment