Created
February 7, 2020 10:32
-
-
Save VinayakBagaria/17ce6d76c1b70d1950565927ab83a391 to your computer and use it in GitHub Desktop.
Fade-in component to animate viewing, no extra dependencies required
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
<FadeIn> | |
<Element>Element 1</Element> | |
<Element>Element 2</Element> | |
<Element>Element 3</Element> | |
<Element>Element 4</Element> | |
<Element>Element 5</Element> | |
<Element>Element 6</Element> | |
</FadeIn> | |
<FadeIn delay={300} transitionDuration={700}> | |
<Element>Element 1</Element> | |
<Element>Element 2</Element> | |
<Element>Element 3</Element> | |
<Element>Element 4</Element> | |
<Element>Element 5</Element> | |
<Element>Element 6</Element> | |
</FadeIn> | |
With Class names | |
<FadeIn className="container" childClassName="child"> | |
<Element>Element 1</Element> | |
<Element>Element 2</Element> | |
<Element>Element 3</Element> | |
<Element>Element 4</Element> | |
<Element>Element 5</Element> | |
<Element>Element 6</Element> | |
</FadeIn> |
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
import React, { useState, useEffect, Children } from 'react'; | |
const FadeIn = ({ | |
delay = 50, | |
transitionDuration = 400, | |
className, | |
childClassName, | |
children, | |
}) => { | |
const [maxIsVisible, setMaxIsVisible] = useState(0); | |
useEffect(() => { | |
let i = 0; | |
const count = Children.count(children); | |
const interval = setInterval(() => { | |
i += 1; | |
if (i > count) { | |
clearInterval(interval); | |
} | |
setMaxIsVisible(i); | |
}, delay); | |
return () => { | |
clearInterval(interval); | |
}; | |
}, []); | |
return ( | |
<div className={className}> | |
{Children.map(children, (child, i) => { | |
const style = { | |
transition: `opacity ${transitionDuration}ms, top ${transitionDuration}ms`, | |
position: 'relative', | |
top: maxIsVisible > i ? 0 : 20, | |
opacity: maxIsVisible > i ? 1 : 0, | |
}; | |
return ( | |
<div className={childClassName} style={style}> | |
{child} | |
</div> | |
); | |
})} | |
</div> | |
); | |
}; | |
export default FadeIn; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment