Created
September 6, 2019 12:48
-
-
Save asci/a6e8f69feb7efbd972bb1e9134a2ba34 to your computer and use it in GitHub Desktop.
Framer X Override for component to fade in when appear on screen
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 * as React from "react" | |
import { useState, useEffect, useRef } from "react" | |
import { Override, motion } from "framer" | |
// Override | |
export function OnScreen(props): Override { | |
const ref = useRef() | |
const [wasShown, setWasShown] = useState(false) | |
const onScreen = useOnScreen(ref) | |
useEffect(() => { | |
if (onScreen) setWasShown(true) | |
}, [onScreen]) | |
const wrapper = ( | |
<motion.div | |
ref={ref} | |
style={{ | |
width: props.width, | |
height: props.height, | |
overflow: "visible", | |
}} | |
animate={{ | |
opacity: onScreen || wasShown ? 1 : 0, | |
scale: onScreen || wasShown ? 1 : 0.8, | |
}} | |
transition={{ | |
duration: 0.3, | |
}} | |
> | |
{props.children} | |
</motion.div> | |
) | |
return { | |
children: wrapper, | |
} | |
} | |
// Hook | |
function useOnScreen(ref, rootMargin = "0px") { | |
// State and setter for storing whether element is visible | |
const [isIntersecting, setIntersecting] = useState(false) | |
useEffect(() => { | |
const observer = new IntersectionObserver( | |
([entry]) => { | |
// Update our state when observer callback fires | |
setIntersecting(entry.isIntersecting) | |
}, | |
{ | |
rootMargin, | |
} | |
) | |
if (ref.current) { | |
observer.observe(ref.current) | |
} | |
return () => { | |
observer.unobserve(ref.current) | |
} | |
}, []) // Empty array ensures that effect is only run on mount and unmount | |
return isIntersecting | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hello,do you know how to use
Data
withmotion.div
?