Skip to content

Instantly share code, notes, and snippets.

@dburles
Created October 23, 2019 06:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dburles/1615e4951a95fe0bc42e628e94ec7899 to your computer and use it in GitHub Desktop.
Save dburles/1615e4951a95fe0bc42e628e94ec7899 to your computer and use it in GitHub Desktop.
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