Created
May 6, 2021 06:43
-
-
Save sarahbethfederman/2df46f7881684d8f339b97aafecae18e to your computer and use it in GitHub Desktop.
Flex gap polyfill
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 { useState, useLayoutEffect, useEffect } from 'react'; | |
// remove this once safari support ships | |
function checkFlexGap() { | |
// create flex container with row-gap set | |
const flex = document.createElement('div'); | |
flex.style.display = 'flex'; | |
flex.style.flexDirection = 'column'; | |
flex.style.rowGap = '1px'; | |
// create two, elements inside it | |
flex.appendChild(document.createElement('div')); | |
flex.appendChild(document.createElement('div')); | |
// append to the DOM (needed to obtain scrollHeight) | |
document.body.appendChild(flex); | |
var isSupported = flex.scrollHeight === 1; // flex container should be 1px high from the row-gap | |
flex?.parentNode?.removeChild(flex); | |
return isSupported; | |
} | |
export function useFlexGap() { | |
const [isFlexGapSupported, setIsFlexGapSupported] = useState<boolean>(false); | |
useEffect(() => { | |
if (document.documentElement.classList.contains('flexbox-gap')) { | |
setIsFlexGapSupported(true); | |
} else if (document.documentElement.classList.contains('no-flexbox-gap')) { | |
setIsFlexGapSupported(false); | |
} | |
}, []); | |
return isFlexGapSupported; | |
} | |
export function useFlexGapPolyfill() { | |
useLayoutEffect(() => { | |
// first check if it's already been run | |
if ( | |
!document.documentElement.classList.contains('flexbox-gap') && | |
!document.documentElement.classList.contains('no-flexbox-gap') | |
) { | |
if (checkFlexGap()) { | |
document.documentElement.classList.add('flexbox-gap'); | |
} else { | |
document.documentElement.classList.add('no-flexbox-gap'); | |
} | |
} | |
}, []); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment