Last active
December 5, 2019 00:56
-
-
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
This file contains hidden or 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
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