Last active
March 10, 2020 10:45
-
-
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
This file contains hidden or 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 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; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
usage