Using Tanstack Router Link with Framer Motion #2375
Replies: 3 comments 3 replies
-
We've recently added docs on using custom link components with TSR. You'll likely need to adapt some of it to work with framer-motion. If you run into any trouble, pop-in to our Discord. Things tend to get a bit lost over here 😅. And if it works, consider maybe adding it to the documentation 👀 |
Beta Was this translation helpful? Give feedback.
-
const MotionLinkForwardRef = forwardRef(
(
props: MotionProps & HTMLAttributes<HTMLAnchorElement>,
ref: Ref<HTMLAnchorElement>,
) => {
return <m.a {...props} ref={ref} />;
},
);
MotionLinkForwardRef.displayName = "MotionLinkForwardRef";
const MotionLink = createLink(MotionLinkForwardRef); |
Beta Was this translation helpful? Give feedback.
-
When I define the Link as you suggested, I am still getting a TypeScript error on the ref. import * as React from 'react'
import { createLink } from '@tanstack/react-router'
import { motion, type HTMLMotionProps } from 'motion/react'
const MotionLinkComponent = React.forwardRef<HTMLAnchorElement, HTMLMotionProps<'a'>>(
(props, ref) => {
return <motion.a {...props} ref={ref} />
}
)
export const MotionLink = createLink(MotionLinkComponent); And then consume it by passing a ref: import * as React from 'react'
function Component() {
const linkRef = React.useRef<HTMLAnchorElement>(null)
return (
<MotionLink
ref={linkRef}
/>
)
} It gives me a type error on the ref:
|
Beta Was this translation helpful? Give feedback.
-
A couple months back I needed to animate a Link with Framer Motion. I have struggled with the implementation; trying both the
createLink
andLinkOptions
APIs. I think I have finally landed on a version others might find good.Note: I will simplify this when React 19 releases to remove the forwardRef.
EDIT: my method didn't work. Here's a good enough version that has the wrong ref:
I scoured the internet looking for someone else's implementation of this. Hopefully it helps! Please let me know what you think of this approach, any feedback or criticism is welcome!
Beta Was this translation helpful? Give feedback.
All reactions