Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Fade in React elements when scrolling in view
// https://dev.to/selbekk/how-to-fade-in-content-as-it-scrolls-into-view-10j4
import React from "react";
import styled from "styled-components";
const Section = styled.div`
opacity: 0;
transform: translateY(20vh);
visibility: hidden;
transition: opacity 1200ms ease-out, transform 600ms ease-out,
visibility 1200ms ease-out;
will-change: opacity, transform, visibility;
&.is-visible {
opacity: 1;
transform: none;
visibility: visible;
}
`;
export default function FadeInSection({ runEffectOnce = true, ...props }) {
const [isVisible, setVisible] = React.useState(false);
const domRef = React.useRef();
React.useEffect(() => {
const setVisibleFn = runEffectOnce
? entry => {
setVisible(currentState => currentState || entry.isIntersecting);
}
: entry => setVisible(entry.isIntersecting);
const observer = new IntersectionObserver(entries => {
entries.forEach(setVisibleFn);
});
observer.observe(domRef.current);
}, [runEffectOnce]);
return (
<Section className={`${isVisible ? "is-visible" : ""}`} ref={domRef}>
{props.children}
</Section>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.