Created
October 23, 2019 06:45
-
-
Save dburles/1615e4951a95fe0bc42e628e94ec7899 to your computer and use it in GitHub Desktop.
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
import { useEffect, useState, useLayoutEffect, useRef } from '../lib/react.js'; | |
import compileStyles from './compile-styles.js'; | |
let globalIdentifier = 0; | |
function css(strings, ...expressions) { | |
const styleElementRef = useRef(document.createElement('style')); | |
const compiledStyles = compileStyles(strings, ...expressions); | |
const [className, setClassName] = useState(); | |
useLayoutEffect(() => { | |
setClassName(`sl-${globalIdentifier}`); | |
globalIdentifier += 1; | |
}, []); | |
useEffect(() => { | |
document.head.appendChild(styleElementRef.current); | |
return () => { | |
styleElementRef.current.remove(); | |
}; | |
}, []); | |
useLayoutEffect(() => { | |
if (className !== undefined) { | |
const style = `.${className} {${compiledStyles}}`; | |
styleElementRef.current.innerHTML = style; | |
} | |
}, [className, compiledStyles]); | |
return className; | |
} | |
export default css; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment