Last active
August 12, 2021 08:25
-
-
Save click2install/f3637f2c5be59844e31c32b795e246aa to your computer and use it in GitHub Desktop.
[useFadeOut] - ReactJS hook to fadeOut an element using the opacity and display styles.
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 {useLayoutEffect, useRef} from "react"; | |
export default function useFadeOut(ref, fadeTime, visible) | |
{ | |
const timerId = useRef(); | |
useLayoutEffect(() => | |
{ | |
clearTimeout(timerId.current); | |
if (ref.current) | |
{ | |
ref.current.style.opacity = visible ? 1 : 0; | |
ref.current.style.transition = `opacity ${fadeTime}ms ease-in-out`; | |
if (visible) | |
{ | |
ref.current.style.display = "block"; | |
} | |
else | |
{ | |
timerId.current = setTimeout(() => {ref.current.style.display = "none";}, fadeTime); | |
} | |
} | |
}, [ref, visible, fadeTime]); | |
} | |
// usage | |
// | |
const loaderRef = useRef(); // the ref to the element to be transitioned | |
useFadeOut(loaderRef, 500, visible); // 500ms transition time, `visible` state variable to trigger the transition |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment