I have a component Fade defined as follows:
const variants = {
hidden: { opacity: 0 },
visible: { opacity: 1 },
};
const Fade = ({ visible, ...rest }) => (
<AnimatePresence initial={false} exitBeforeEnter>
{visible && (
<motion.div
initial="hidden"
animate="visible"
exit="hidden"
{...{ variants, ...rest }}
/>
)}
</AnimatePresence>
);
Note: I've removed some of the type definitions.
This component can be used like any other component in React (eg: <Fade />).
My goal is to create a utility that can be used like this:
const myFadingDiv = <fade.div />;
or
const myFadingSection = <fade.section />
Ideally, I would want something similar to motion, that can wrap existing components like this:
const FadingCustom = fade(CustomComponent);
I've tried this:
const fade = {
div: ({ visible, ...rest }) => (
<AnimatePresence initial={false} exitBeforeEnter>
{visible && (
<motion.div
initial="hidden"
animate="visible"
exit="hidden"
{...{ variants, ...rest }}
/>
)}
</AnimatePresence>
),
};
Edit
Here's a quick update on what I've tried:
const fade = new Proxy(motion, { get: (target, tag) => { const Component = target[tag]; return ({ visible, ...rest }: { visible: boolean }) => ( <AnimatePresence initial={false} exitBeforeEnter> {visible && ( <Component initial="hidden" animate="visible" exit="hidden" {...{ variants, ...rest }} /> )} </AnimatePresence> ); }, });This works well, but I don't have IntelliSense for the
visibleprop.
How can I create a utility like motion that can extend the above feature for any tag?
I would prefer to avoid the as prop since I would want IntelliSense to suggest the props that the component can take based on its tag. I would also like to set appropriate type definitions in TypeScript, to direct IntelliSense.
Any help is greatly appreciated! Thank you for your time!