useCssVar
Manipulate CSS variables
Usage
Live Editor
function Demo() { const key = "--color"; const ref = useRef<HTMLDivElement>(null); const [color, setColor] = useCssVar(key, ref, ""); const style: any = { "--color": "#7fa998", "color": "var(--color)", }; const switchColor = () => { if (color === "#df8543") { setColor("#7fa998"); } else { setColor("#df8543"); } }; return ( <section> <div ref={ref} style={style}> Sample text, <>{color}</> </div> <button onClick={switchColor}>Change Color</button> </section> ); }
Result
Loading...
API
useCssVar
Returns
readonly [string, (v: string) => void]
: A tuple with the following elements:
- The current value of the css var.
- A function to update the value of the css var.
Arguments
Argument | Description | Type | DefaultValue |
---|---|---|---|
prop | prop, eg: --color | string (Required) | - |
target | dom element | BasicTarget<T> (Required) | - |
defaultValue | default value | string | undefined | - |
options | options | UseCssVarOptions | undefined | - |
UseCssVarOptions
Property | Description | Type | DefaultValue |
---|---|---|---|
observe | Use MutationObserver to monitor variable changes | boolean | false |
BasicTarget
export type BasicTarget<T extends TargetType = Element> = (() => TargetValue<T>) | TargetValue<T> | MutableRefObject<TargetValue<T>>;
TargetValue
type TargetValue<T> = T | undefined | null;
TargetType
type TargetType = HTMLElement | Element | Window | Document | EventTarget;