-
-
Save nullhook/52e0f615f728559080f0c048613c27a3 to your computer and use it in GitHub Desktop.
Add !important to react element
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
class Counter { static id = 10000; } | |
function useId(prefix) { | |
const id = React.useRef(); | |
if (!id.current) { | |
Counter.id += 1; | |
id.current = `__${prefix}__${Counter.id}`; | |
} | |
return id.current; | |
} | |
function Styled({ children, style }) { | |
const id = useId('styled'); | |
const styleRef = React.useRef(); | |
const apply = () => { | |
const { sheet } = styleRef.current; | |
sheet.insertRule(`#${id} + * {}`); | |
const index = sheet.rules.length - 1; | |
Object.entries(style).forEach(([k,v]) => { | |
if (typeof v === 'number') { | |
v = String(v) + 'px'; | |
} | |
if (!v) return; | |
const k2 = k.replace(/([A-Z])/g, '-$1').toLowerCase(); | |
const v2 = v.replace(/\s+!important\s*$/, ''); | |
if (v !== v2) { | |
sheet.rules[index].style.setProperty(k2, v2, 'important'); | |
} else { | |
sheet.rules[index].style.setProperty(k2, v2); | |
} | |
}); | |
if (index > 0) { | |
sheet.removeRule(0); | |
} | |
} | |
React.useEffect(() => { | |
apply(); | |
}, [style]); | |
return ( | |
<React.Fragment> | |
<style id={id} ref={styleRef} /> | |
{children} | |
</React.Fragment> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This can be used to style third party components