Using Tanstack Router Link with Framer Motion #2375
Closed
KirillTregubov
started this conversation in
General
Replies: 4 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 👀 |
0 replies
const MotionLinkForwardRef = forwardRef(
(
props: MotionProps & HTMLAttributes<HTMLAnchorElement>,
ref: Ref<HTMLAnchorElement>,
) => {
return <m.a {...props} ref={ref} />;
},
);
MotionLinkForwardRef.displayName = "MotionLinkForwardRef";
const MotionLink = createLink(MotionLinkForwardRef); |
0 replies
|
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: |
3 replies
|
For anyone stumbling upon this thread, the original code snippet creates a Motion link on React 19, Vite 8 and latest TanStack Router: import { createLink } from '@tanstack/react-router'
import { motion } from 'framer-motion'
export const MotionLink = createLink(motion.a) |
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
A couple months back I needed to animate a Link with Framer Motion. I have struggled with the implementation; trying both the
createLinkandLinkOptionsAPIs. 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!
All reactions