-
Hey everyone, based on the Slot documentation, when your component has a single children element, a polymorphic button can be created accordingly: // your-button.jsx
import React from 'react';
import { Slot } from '@radix-ui/react-slot';
function Button({ asChild, ...props }) {
const Comp = asChild ? Slot : 'button';
return <Comp {...props} />;
} What if you want to pre-configure the Button component to provide some basic animation using framer-motion? Problem With framer-motion, this can be achieved using Motion Component accordingly: function Button({ ..props }) {
return <motion.button whileTap={{ scale: 0.9 }} {...props} />;
} How do we achieve the same behavior with the polymorphic button that uses Slot? What I've tried: I tried to wrap Slot with the My Button component: export interface ButtonProps extends HTMLMotionProps<'div'> {
asChild?: boolean;
}
const MotionSlot = motion(Slot);
const Button = forwardRef<HTMLButtonElement, ButtonProps>(
({ asChild = false, ...props }, ref) => {
const Comp = asChild ? MotionSlot : motion.button;
return <Comp whileTap={{ scale: 0.9 }} ref={ref} {...props} />;
}
);
Button.displayName = 'Button'; Typescript error:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Ok, so I've managed to implement something that works. Link to my original answer: https://stackoverflow.com/a/78655398/8997321
|
Beta Was this translation helpful? Give feedback.
Ok, so I've managed to implement something that works. Link to my original answer: https://stackoverflow.com/a/78655398/8997321