Skip to content

Instantly share code, notes, and snippets.

@ededejr
Created May 24, 2024 03:12
Show Gist options
  • Save ededejr/de8d3e3341f5dd543b77958314ddcb56 to your computer and use it in GitHub Desktop.
Save ededejr/de8d3e3341f5dd543b77958314ddcb56 to your computer and use it in GitHub Desktop.
use the current css color of a passed ref or the document
import type React from "react";
import { useEffect, useState } from "react";
export function useCurrentColorValue(ref?: React.RefObject<HTMLElement>) {
const [color, setColor] = useState<string | null>(null);
useEffect(() => {
const updateColor = () => {
if (ref?.current) {
setColor(getComputedStyle(ref.current).color);
} else {
// use document color
setColor(getComputedStyle(window.document.documentElement).color);
}
};
const observer = new MutationObserver(() => {
updateColor();
});
// observe the root element for changes
observer.observe(window.document.documentElement, {
attributes: true,
attributeFilter: ["class", "style"],
});
if (ref?.current) {
// observe the container element for changes
observer.observe(ref.current, {
attributes: true,
attributeFilter: ["class", "style"],
});
}
updateColor();
return () => observer.disconnect();
}, [ref]);
return color;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment