Access parent ref from child for framer motion useElementScroll

Viewed 274

I have the following 2 components:

App.tsx

import { useRef, VFC } from "react";

import Card from "./Card";

const App: VFC = () => {
  const scrollRef = useRef<HTMLDivElement>(null);

  return (
    <div ref={scrollRef}>
      <Card scrollRef={scrollRef} />
    </div>
  );
};

export default App;

Card.tsx

import { useElementScroll } from "framer-motion";
import { FC, RefObject } from "react";

interface CardProps {
  scrollRef: RefObject<HTMLElement>;
}

const Card: FC<CardProps> = ({ scrollRef }) => {
  const { scrollY } = useElementScroll(scrollRef);
  console.log(scrollY);
  return null;
};

export default Card;

The Card component now throws the following error:

ref provided to useScroll must be passed into a HTML element.

The only difference between my example and the example in the Framer Motion docs is I'm getting the ref from the parent component rather than the child. I don't understand the error it's throwing. Can anyone help explain?

Live example here:

https://codesandbox.io/s/framer-motion-scroll-ref-p3bqq

1 Answers

Just use the useElementScroll() hook inside the parent component where the scrollRef element actually exists.

Then, instead of passing scrollRef into the child component just pass the necessary value from useElementScroll(), which would be scrollY in your case.

This worked for me.

Related