I'm looking to build an intersection observer component in a personal Gatsby project. The reason for it is the animation and trigger is the same in different areas of the site. What I have so far:
// Observer.js
import React, { useEffect, useRef } from "react";
import { useAnimation } from "framer-motion";
const Observer = ({ children }) => {
const controls = useAnimation();
const ref = useRef();
useEffect(() => {
const observer = new IntersectionObserver(
([entry]) => {
if (entry.isIntersecting) {
controls.start({
opacity: 1,
transition: { duration: 0.75, delay: 0.75 },
});
}
},
{
root: null,
rootMargin: "0px",
threshold: 0.1,
}
);
if (ref.current) {
observer.observe(ref.current);
}
}, [ref]);
return <div ref={ref}>{children}</div>;
};
export default Observer;
What I am looking to do is access controls in the children of the Observer.js component.
// ChildComponent.js
const ChildComponent= (props) => {
return (
<Observer>
<div>
<motion.div
initial={{ opacity: 0 }}
animate={props.controls}
>
<h2>This will animate on scroll</h2>
</motion.div>
</div>
</Observer>
);
};
export default ChildComponent;
I have seen answers such as - Pass props from layout to children in Gatsby - but I get the error props.children is not a function when attempting this.
Is what I am looking to do possible, or is there a better way of achieving this?