Skip to content

Instantly share code, notes, and snippets.

@cbdyzj
Created January 23, 2022 05:24
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 cbdyzj/b52c2d9383d43b8e327c20a534269dfe to your computer and use it in GitHub Desktop.
Save cbdyzj/b52c2d9383d43b8e327c20a534269dfe to your computer and use it in GitHub Desktop.
const classNameSet = new Set()
function getRandomClassName() {
const className = Math.random().toString(36).substring(2)
if (classNameSet.has(className)) {
return getRandomClassName()
}
classNameSet.add(className)
return `css-${className}`
}
function injectStyle(cssText) {
const styleRef = document.createElement('style')
styleRef.innerHTML = cssText
document.head.appendChild(styleRef)
}
export default function css(strings, ...keys) {
const className = getRandomClassName()
const cssText = strings.map((s, i) => s + (keys[i] ?? '')).join('').replace(/&/g, `.${className}`)
injectStyle(cssText)
return className
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment