Skip to main content

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

ArgumentDescriptionTypeDefaultValue
propprop, eg: --colorstring (Required)-
targetdom elementBasicTarget<T> (Required)-
defaultValuedefault valuestring | undefined-
optionsoptionsUseCssVarOptions | undefined-

UseCssVarOptions

PropertyDescriptionTypeDefaultValue
observeUse MutationObserver to monitor variable changesbooleanfalse

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;