Appearance
useStyleTag
Inject reactive style element in head.
Demo
Usage
Basic usage
Provide a CSS string, then useStyleTag will automatically generate an id and inject it in <head>.
tsx
import { useStyleTag } from '@reause/core'
const [css, setCss, { id, load, unload, isLoaded }] = useStyleTag('.foo { margin-top: 32px; }')
// Later you can modify styles
setCss('.foo { margin-top: 64px; }')This code will be injected to <head>:
html
<style id="reause_styletag_1">
.foo {
margin-top: 64px;
}
</style>Custom ID
If you need to define your own id, you can pass id as first argument.
tsx
useStyleTag('.foo { margin-top: 32px; }', { id: 'custom-id' })html
<!-- injected to <head> -->
<style id="custom-id">
.foo {
margin-top: 32px;
}
</style>Media query
You can pass media attributes as last argument within object.
tsx
useStyleTag('.foo { margin-top: 32px; }', { media: 'print' })html
<!-- injected to <head> -->
<style id="reause_styletag_1" media="print">
.foo {
margin-top: 32px;
}
</style>Type Declarations
ts
export interface UseStyleTagOptions {
media?: string;
immediate?: boolean;
manual?: boolean;
id?: string;
nonce?: string;
document?: Document;
}
export type UseStyleTagReturn = readonly [
css: string,
setCss: Dispatch<SetStateAction<string>>,
controls: {
id: string;
load: () => void;
unload: () => void;
isLoaded: boolean;
}
]
export function useStyleTag(css: string, options?: UseStyleTagOptions): UseStyleTagReturn