Skip to content

Instantly share code, notes, and snippets.

@DominicTobias
Last active Mar 9, 2020
Embed
What would you like to do?
Simple no-frills CSS-In-JSS in React
/*
Why?
- Tiny compared to existing solutions
- No frills or stupid class hashing, just for portability of providing components with CSS included
- Discourage dynamism -> While the CSS will update if you pass in variables, `insertRule` is more
efficient for highly dynamic CSS. But highly dynamic CSS is a code smell. Conditional selectors and
CSS Variables can achieve most use cases whilst being far more performant.
*/
import { useRef, useEffect } from 'react';
interface CSSProps {
children: string;
}
export function CSS({ children }: CSSProps): null {
const styleSheet = useRef(typeof document !== 'undefined' && document.createElement('style'));
useEffect(() => {
const ref = styleSheet.current;
if (ref) {
ref.type = 'text/css';
document.head.appendChild(ref);
}
return (): void => {
if (ref) {
document.head.removeChild(ref);
}
};
}, []);
useEffect(() => {
if (styleSheet.current) {
styleSheet.current.innerText = children;
}
}, [children]);
return null;
}
<CSS>{`
.grid {
position: relative;
width: ${width}px; // Remember that very fast updates especially to large chunks of CSS are not as performant as using `insertRule` API
height: ${height}px;
overflow: auto;
box-sizing: border-box;
}
.grid * {
box-sizing: border-box;
}
`}</CSS>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment