Skip to content

Instantly share code, notes, and snippets.

@isabellachen
Last active March 10, 2020 10:45
Show Gist options
  • Save isabellachen/f5daf5008c5a91592d288a4df08a6782 to your computer and use it in GitHub Desktop.
Save isabellachen/f5daf5008c5a91592d288a4df08a6782 to your computer and use it in GitHub Desktop.
useChromeBackground hook determines background-color of DOM element and sets the the color for adequate contrast
import chroma from 'chroma-js';
import { MutableRefObject, useEffect, useRef } from 'react';
export const useChromaBackground = (): MutableRefObject<HTMLElement> => {
const tagRef = useRef<HTMLElement>({} as HTMLElement);
const cWhite = '#FFFFFF';
const minClarityValue = 70;
useEffect(() => {
async function validateBackground() {
if (!tagRef || !tagRef.current) {
return;
}
const bgColor = await window.getComputedStyle(tagRef.current).getPropertyValue('background-color');
const levelOfClarity = chroma(bgColor).get('lab.l');
if (levelOfClarity < minClarityValue) {
tagRef.current.style.color = cWhite;
}
}
validateBackground();
}, [tagRef.current]);
return tagRef;
};
@isabellachen
Copy link
Author

usage

export function TopMenu() {
  const tagRef = useChromaBackground();
  const logoFile = settings && settings.logoImageUrl ? settings.logoImageUrl : sidralogoFile;

  return (
    <div className="top-menu">
      <div>
        <img className="top-menu__logo-container" alt={logoFile} src={logoFile} />
        <span ref={tagRef} className="top-menu__env">
          {settings && settings.environment}
        </span>
      </div>
  );
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment