Last active
April 9, 2021 14:24
-
-
Save bpierre/9d861a308dce3beee95be41dd72861bc to your computer and use it in GitHub Desktop.
Custom CSS units implemented with @emotion/cache as a stylis plugin
This file contains 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 { CacheProvider } from "@emotion/react" | |
import createCache from "@emotion/cache" | |
function cssUnitPlugin(unitInPx = 8, unit = "gu") { | |
const re = new RegExp("([0-9]+)" + unit, "g") | |
const convert = (value) => value.replace(re, replacer) | |
const replacer = (_, value) => `${value * unitInPx}px` | |
return (element) => { | |
if (element.type === "decl" && element.value.includes(unit)) { | |
element.value = convert(element.value) | |
} | |
} | |
} | |
const cache = createCache({ | |
key: "css", | |
stylisPlugins: [ cssUnitPlugin(8, "gu") ], | |
}) | |
export function App({ children }) { | |
return ( | |
<CacheProvider value={cache}> | |
// … | |
</CacheProvider> | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment