4

I am trying to create a React website using Framer Motion, the problem is that my animation looks good in desktop view, but not really in mobile. Now I want to disable the animation. How do I do this?

dasJulian
  • 497
  • 6
  • 21
iamkyo
  • 71
  • 1
  • 2
  • 7

3 Answers3

11

Without knowing further details, I would recommend using Variants for this. Inside your functional component, create a variable that checks for mobile devices. Then, only fill the variants if this variable is false. Note that it doesn't work when you resize the page. The component must get rerendered.

I've created a codesandbox for you to try it out!

For further information on Variants, check this course

dasJulian
  • 497
  • 6
  • 21
4

Another simple way I just did myself when this exact question came up. Below we are using a ternary operatory to generate a object which we then spread using the spread syntax

const attributes = isMobile ? {
    drag: "x",
    dragConstraints: { left: 0, right: 0 },
    animate: { x: myVariable },
    onDragEnd: myFunction
} : { onMouseOver, onMouseLeave };

<motion.div {...attributes}> {/* stuff */} </motion.div>

As you can see I want onMouseEnter & onMouseLeave on desktop with no animations. On mobile I want the opposite. This is working of me perfectly. Hope this helps too.

Daniel

GaddMaster
  • 331
  • 3
  • 14
1

This is how we've done it:

import {
  type ForwardRefComponent,
  type HTMLMotionProps,
  motion as Motion,
} from 'framer-motion';
import { forwardRef } from 'react';

const ReducedMotionDiv: ForwardRefComponent<
  HTMLDivElement,
  HTMLMotionProps<'div'>
> = forwardRef((props, ref) => {
  const newProps = {
    ...props,
    animate: undefined,
    initial: undefined,
    transition: undefined,
    variants: undefined,
    whileDrag: undefined,
    whileFocus: undefined,
    whileHover: undefined,
    whileInView: undefined,
    whileTap: undefined,
  };

  return <Motion.div {...newProps} ref={ref} />;
});

export const motion = new Proxy(Motion, {
  get: (target, key) => {
    if (key === 'div') {
      return ReducedMotionDiv;
    }

    // @ts-expect-error - This is a proxy, so we can't be sure what the key is.
    return target[key];
  },
});

export {
  AnimatePresence,
  type Variants,
  type HTMLMotionProps,
  type MotionProps,
  type TargetAndTransition,
  type Transition,
  type Spring,
} from 'framer-motion';

Same principle as other answers, just complete example.

Gajus
  • 69,002
  • 70
  • 275
  • 438