/
style.js
40 lines (34 loc) · 1.01 KB
/
style.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import React from 'react'
import { useStyleRegistry } from './stylesheet-registry'
import { computeId } from './lib/hash'
// Opt-into the new `useInsertionEffect` API in React 18, fallback to `useLayoutEffect`.
// https://github.com/reactwg/react-18/discussions/110
const useInsertionEffect = React.useInsertionEffect || React.useLayoutEffect
export default function JSXStyle(props) {
const registry = useStyleRegistry()
// If `registry` does not exist, we do nothing here.
if (!registry) {
return null
}
if (typeof window === 'undefined') {
registry.add(props)
return null
}
useInsertionEffect(() => {
registry.add(props)
return () => {
registry.remove(props)
}
// props.children can be string[], will be striped since id is identical
}, [props.id, String(props.dynamic)])
return null
}
JSXStyle.dynamic = info => {
return info
.map(tagInfo => {
const baseId = tagInfo[0]
const props = tagInfo[1]
return computeId(baseId, props)
})
.join(' ')
}