Skip to content

Instantly share code, notes, and snippets.

@VinayakBagaria
Created February 7, 2020 10:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save VinayakBagaria/17ce6d76c1b70d1950565927ab83a391 to your computer and use it in GitHub Desktop.
Save VinayakBagaria/17ce6d76c1b70d1950565927ab83a391 to your computer and use it in GitHub Desktop.
Fade-in component to animate viewing, no extra dependencies required
<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>
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