Last active
March 9, 2020 15:23
-
-
Save dominictobias/90d7a9e1e7737a0f9dbf0756b07bb05a to your computer and use it in GitHub Desktop.
Simple no-frills CSS-In-JSS in React
This file contains hidden or 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
| /* | |
| 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; | |
| } |
This file contains hidden or 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
| <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