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