Skip to content

Instantly share code, notes, and snippets.

@ludder
Created February 4, 2020 19:42
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 ludder/75fe728d2a4866db564e31a3fa9d979f to your computer and use it in GitHub Desktop.
Save ludder/75fe728d2a4866db564e31a3fa9d979f to your computer and use it in GitHub Desktop.
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