Skip to content

Instantly share code, notes, and snippets.

@asci
Created September 6, 2019 12:48
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save asci/a6e8f69feb7efbd972bb1e9134a2ba34 to your computer and use it in GitHub Desktop.
Save asci/a6e8f69feb7efbd972bb1e9134a2ba34 to your computer and use it in GitHub Desktop.
Framer X Override for component to fade in when appear on screen
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
}
@MrKou47
Copy link

MrKou47 commented Jul 22, 2020

Hello,do you know how to use Data with motion.div?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment