Last active
June 20, 2019 01:09
-
-
Save trainiac/2b21849a58ab09f09a3d7fd0e6d5b0bc to your computer and use it in GitHub Desktop.
A React hook to assist in animating a component on mount and destroy.
This file contains 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
/* | |
When you want to add a component to the DOM and have it animate on mount | |
you have to give a little delay before changing the css to | |
trigger a css animation. Otherwise the css transition doesn't work. | |
When you want to remove a component from the DOM and have it animate before | |
being removed you have to wait until an animation is complete. | |
This gives you two pieces of state to make that easy. | |
*/ | |
import { useState, useEffect } from 'react' | |
function queueTask(task: () => void, delay: number) { | |
const timeoutId = setTimeout(() => { | |
task() | |
}, delay) | |
return () => { | |
clearTimeout(timeoutId) | |
} | |
} | |
export default function useReveal( | |
isOpen: boolean, | |
animationDelay: number, | |
animationDuration: number | |
) { | |
const [isRendered, setIsRendered] = useState(false) | |
const [isRevealed, setIsRevealed] = useState(false) | |
useEffect(() => { | |
if (isOpen) { | |
setIsRendered(true) | |
return queueTask(() => { | |
setIsRevealed(true) | |
}, animationDelay) | |
} | |
setIsRevealed(false) | |
return queueTask(() => { | |
setIsRendered(false) | |
}, animationDuration) | |
}, [isOpen, animationDelay, animationDuration]) | |
return [isRendered, isRevealed] | |
} | |
// USAGE | |
import styled from 'styled-components' | |
const duration = 300 | |
const delay = 10 | |
const Container = styled.div` | |
position: fixed; | |
z-index: 10; | |
top: 0; | |
left: 0; | |
width: 100vw; | |
height: 100vh; | |
background-color: rgba(0, 0, 0, 0.5); | |
transition: opacity ${duration}ms ease; | |
opacity: ${prop => (prop.reveal ? 0.5 : 0)}; | |
` | |
export default function Mask({ isOpen }) { | |
const [isRendered, isRevealed] = useReveal(isOpen, delay, duration) | |
return isRendered ? ( | |
<Container reveal={isRevealed} /> | |
) : null | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment