Created
May 24, 2024 03:12
-
-
Save ededejr/de8d3e3341f5dd543b77958314ddcb56 to your computer and use it in GitHub Desktop.
use the current css color of a passed ref or the document
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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