File size: 2,025 Bytes
1e92f2d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 |
import { useState, useEffect } from 'react';
/**
* Custom hook to read CSS variables
* @param variableName - The CSS variable name (including the -- prefix)
* @param element - The element to read the variable from (defaults to :root)
* @param observe - Whether to observe for changes to the variable
* @returns The value of the CSS variable
* @example
* // Basic usage
* const primaryColor = useCssVariable('--primary-color');
* @example
* // Reading from a specific element and observing changes
* const headerHeight = useCssVariable('--header-height', headerRef.current, true);
*/
function useCssVariable(
variableName: string,
element: Element | null = typeof document !== 'undefined' ? document.documentElement : null,
observe: boolean = false
): string {
const [ value, setValue ] = useState< string >( '' );
useEffect( () => {
// Check if we're in a browser environment
if ( typeof window === 'undefined' ) {
return;
}
// Make sure the element exists
if ( ! element ) {
return;
}
// Function to get the current value of the CSS variable
const updateValue = (): void => {
const styles = window.getComputedStyle( element );
const newValue = styles.getPropertyValue( variableName ).trim();
setValue( newValue );
};
// Get the initial value
setTimeout( updateValue, 200 );
// Set up observer for changes if requested
if ( observe ) {
const observer = new MutationObserver( ( mutations: MutationRecord[] ): void => {
mutations.forEach( ( mutation: MutationRecord ): void => {
if (
mutation.type === 'attributes' &&
( mutation.attributeName === 'style' || mutation.attributeName === 'class' )
) {
updateValue();
}
} );
} );
observer.observe( element, {
attributes: true,
attributeFilter: [ 'style', 'class' ],
} );
// Clean up observer when component unmounts
return () => observer.disconnect();
}
}, [ variableName, element, observe ] );
return value;
}
export default useCssVariable;
|