Skip to content

Instantly share code, notes, and snippets.

@nullhook

nullhook/.jsx Secret

Last active November 7, 2019 12:50
Show Gist options
  • Save nullhook/52e0f615f728559080f0c048613c27a3 to your computer and use it in GitHub Desktop.
Save nullhook/52e0f615f728559080f0c048613c27a3 to your computer and use it in GitHub Desktop.
Add !important to react element
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>
);
}
@nullhook
Copy link
Author

nullhook commented Nov 7, 2019

This can be used to style third party components

<Styled style={{}}>
<ThirdPartyComponent />
</Styled>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment