Skip to content

Instantly share code, notes, and snippets.

@iffa
Last active January 11, 2022 16:25
Show Gist options
  • Save iffa/d90108e83ae27ee5c8aebde19edf8bb8 to your computer and use it in GitHub Desktop.
Save iffa/d90108e83ae27ee5c8aebde19edf8bb8 to your computer and use it in GitHub Desktop.
Extended Chakra UI Flex-component with support for Framer Motion animations. (with TypeScript typings!)
export type MotionBoxProps = Omit<FlexProps, keyof MotionProps> &
MotionProps & {
as?: React.ElementType;
};
export const MotionBox = motion.custom(
forwardRef<MotionBoxProps, 'div'>((props, ref) => {
const chakraProps = Object.fromEntries(
// do not pass framer props to DOM element
Object.entries(props).filter(([key]) => !isValidMotionProp(key))
);
return <Flex ref={ref} {...chakraProps} />;
})
) as ComponentWithAs<'div', MotionBoxProps>;
@bravo-kernel
Copy link

For motion v4/v5:

import React from "react"
import { Flex, FlexProps, forwardRef, ComponentWithAs } from "@chakra-ui/react"
import { motion, MotionProps, isValidMotionProp } from "framer-motion"

export type MotionBoxProps = Omit<FlexProps, keyof MotionProps> &
  MotionProps & {
    as?: React.ElementType
  }

export const MotionBoxFlex = motion(
  forwardRef<MotionBoxProps, "div">((props, ref) => {
    const chakraProps = Object.fromEntries(
      // do not pass framer props to DOM element
      Object.entries(props).filter(([key]) => !isValidMotionProp(key))
    )
    return <Flex ref={ref} {...chakraProps} />
  })
) as ComponentWithAs<"div", MotionBoxProps>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment