How do I turn off Framer Motion animations in mobile view? - reactjs

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?

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

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

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.

Related

Jest assert on style after animate is performed

I have a React Application using Jest and React Testing Library for unit testing. I have difficulties asserting that a component's style has changed. My component takes in an isSelected boolean and performs an animation based on that.
My component: (Using framer-motion)
const MotionImage = motion(Image);
const SCALE_SIZE = 1.5;
export interface IPreviewer{
isSelected: boolean;
}
export function Previewer({
isSelected,
}: IPreviewer): JSX.Element {
return (
<MotionImage
animate={{
scale: isSelected ? SCALE_SIZE : 1,
}}
/>
);
}
My test:
test("Component when isSelected highlights the image", () => {
const { debug } = render(
<Previewer
isSelected
/>
);
const image = screen.getByRole("img");
debug(image);
expect(image).toHaveStyle("transform: scale(1.5) translateZ(0)");
});
The test debug giving me:
<img
class="chakra-image css-yk396h"
src="http://placeimg.com/222.07846627773333/3.4102996091771587"
style="transform: none;"
/>
As you can see the img is found but the style is not as expected: style="transform: none;"
I will appreciate any suggestions on how to test this right?
Note
Setting initial={false} to the component itself will make the test pass but will lose the initial animation so I will avoid that.
Introducing a timeOut promise inside the test before asserting will work, but I would like to avoid that as well.
waitFor should help you to wait for the styles. https://testing-library.com/docs/dom-testing-library/api-async/#waitfor

React useState not rendering with objects

The Button Component has a event listener onClick which calls changeTheme(). The Content component is a div with some text which is passed a theme prop 'style'. When I click the button, the theme is changed for 2 consecutive clicks. After that no matter how many times I click the button, theme doesn't change.Why is that?
function ParentElement() {
const dark={
color:'white',
backgroundColor:'darkgray',
}
const light={
color:'darkgray',
backgroundColor:'white'
}
const [currentTheme,setTheme]=useState(light)
function changeTheme(e){
//toggle theme
currentTheme==light?setTheme(dark):setTheme(light)
}
return (
<div>
<Button changeTheme={changeTheme}/>
<Content style={currentTheme} />
</div>
)
}
function Content({style}) {
return (
<div style={style}>
Lorem ipsum dolor sit amet consectetur adipisicing elit.
</div>
)
}
It stops working after two times because you are comparing object references, which are changing after the call to setState.
Since currentTheme is initialized to light, the first call to currentTheme == light ? setTheme(dark) : setTheme(light) goes in "the true branch" and sets currentTheme to dark. However setTheme — as any change of state object in React — returns a new object reference, so from this point onwards currentTheme reference will be different from the reference of light or even of dark, although at this point the theme is dark.
Therefore, from now the condition always go in "the false branch", which sets the theme to light.
In JavaScript, a comparison of objects as you are doing is a comparison of references.
You can fix the issue by e.g. comparing the theme name (a string), as it will be a comparison by value:
function ParentElement() {
const dark = {
name: 'dark',
style: {
color: 'white',
backgroundColor: 'darkgray'
}
}
const light = {
name: 'light',
style: {
color: 'darkgray',
backgroundColor: 'white'
}
}
const [currentTheme, setTheme] = useState(light)
function changeTheme(e) {
//toggle theme
currentTheme.name === light.name ? setTheme(dark) : setTheme(light)
console.log(currentTheme);
}
return (
<div>
<Button changeTheme={changeTheme}/>
<Content style={currentTheme.style} />
</div>
)
}
You can also do this way and archive this.
import React, { useState, useMemo } from "react";
const themes = {
dark: {
color: "white",
backgroundColor: "darkgray"
},
light: {
color: "darkgray",
backgroundColor: "white"
}
};
function ParentElement() {
const [themeMode, setThemeMode] = useState("light");
const changeTheme = (e) => {
//toggle theme
const newThemeMode = themeMode === "light" ? "dark" : "light";
setThemeMode(newThemeMode);
};
const currentTheme = useMemo(() => {
return themes[themeMode];
}, [themeMode]);
return (
<div>
<button onClick={changeTheme}>change Theme</button>
<Content style={currentTheme} />
</div>
);
}
Just in case you would like to understand what is actually happening here:
light is an object. When you set the default theme by useState(light) react sets a reference to the light object.
In your changeTheme handler, you are checking if the currentTheme and light are referencing the same object currentTheme==light, you are not checking if they are similar. That is in fact a huge difference here. On the first click, the outcome is true and the theme switches to dark.
On the second click, the theme switches to light but this time react is deep copying the light object under the hood. The reference to the light object is lost. Every time you check for currentTheme==light, the outcome will be false from now on, and the theme will never switch to dark again.
To solve this, you would have to make a deepEqual check (not recommended) or introduce another flag or variable to track the currently selected theme.
Reacts useState hook sets state asynchronous, which means it won't do it immediately. In this case, when you might want to use the useState callback. So try this:
currentTheme === light ? setTheme(() => dark) : setTheme(() => light)
I would also consider doing the check for current theme with the help of the callback, to make sure you compare with the actual state, like so:
setTheme((prevTheme) => prevTheme === light ? dark : light)
What I've learned is that when you want to modify your state based on the previous one, you want to take the previous state from the statehook callback, which makes sure you get the previous state.
first light will always be true since Boolean({}) will always resolve to true... you need to to check for example themes[key] and toggle based on that

How to animate react-native-svg Polygon element?

Is there a simple way to animate the Polygon element from the react-native-svg library?
I need to animate his shape by animating the points.
I found few examples on how to animate Path element or Circle, but couldn't find anything regarding the Polygon. Thanks in advance.
Bit late to the party, but I've found a solution if you're still interested. It's not exactly 'simple', but it works. There's a library called React Native Reanimated, and it extends the functionality of Animated components
substantially. Here's what I was able to achieve:
The reason animating Polygons isn't available out of the box is because the standard Animated API only handles simple values, namely individual numbers. The Polygon component in react-native-svg takes props of points, which is an array of each of the points, themselves array of x and y. For example:
<Polygon
strokeWidth={1}
stroke={strokeColour}
fill={fillColour}
fillOpacity={1}
points={[[firstPointX, firstPointY],[secondPointX, secondPointY]}
/>
React Native Reanimated allows you to animate even complex data types. In this case, there is useSharedValue, which functions almost identical to new Animated.value(), and a function called useAnimatedProps, where you can create your points (or whatever else you want to animate) and pass them to the component.
// import from the library
import Animated, {
useSharedValue,
useAnimatedProps,
} from 'react-native-reanimated';
// creates the animated component
const AnimatedPolygon = Animated.createAnimatedComponent(Polygon);
const animatedPointsValues = [
{x: useSharedValue(firstXValue), y: useSharedValue(firstYValue)},
{x: useSharedValue(secondXValue), y: useSharedValue(secondYValue)},
];
const animatedProps = useAnimatedProps(() => ({
points: data.map((_, i) => {
return [
animatedPointValues[i].x.value,
animatedPointValues[i].y.value,
];
}),
})),
Then in your render/return:
<AnimatedPolygon
strokeWidth={1}
stroke={strokeColour}
fill={fillColour}
fillOpacity={1}
animatedProps={animatedProps}
/>
Then whenever you update one of those shared values, the component will animate.
I'd recommend reading their docs and becoming familiar with the library, as it will open up a whole world of possibilities:
https://docs.swmansion.com/react-native-reanimated/
Also, the animations are handled in the native UI thread, and easily hit 60fps, yet you can write them in JS.
Good luck!
react-native-reanimated also supports flat arrays for the Polygon points prop, so we can simplify the animation setup even more.
Full example which will animate the react-native-svg's Polygon when the points prop changes looks like this:
import React, { useEffect } from 'react'
import Animated, { useAnimatedProps, useSharedValue, withTiming } from 'react-native-reanimated'
import { Polygon } from 'react-native-svg'
interface Props {
points: number[]
}
const AnimatedPolygonInternal = Animated.createAnimatedComponent(Polygon)
export const AnimatedPolygon: React.FC<Props> = ({ points }: Props) => {
const sharedPoints = useSharedValue(points)
useEffect(() => {
sharedPoints.value = withTiming(points)
}, [points, sharedPoints])
const animatedProps = useAnimatedProps(() => ({
points: sharedPoints.value,
}))
return <AnimatedPolygonInternal fill="lime" animatedProps={animatedProps} />
}

Custom page / route transitions in Next.js

I'm trying to achieve callback-based route transitions using Next.js's framework and Greensock animation library (if applicable). For example when I start on the homepage and then navigate to /about, I want to be able to do something like:
HomepageComponent.transitionOut(() => router.push('/about'))
ideally by listening to the router like a sort of middleware or something before pushing state
Router.events.on('push', (newUrl) => { currentPage.transitionOut().then(() => router.push(newUrl)) });
Main Problem
The main problem is that I also have a WebGL app running in the background, decoupled from the React ecosystem (since it uses requestAnimationFrame). So the reason I want callback-based transitions is because I need to run them after the WebGL transitions are done.
Current Implementation
I've looked into using React Transition Group and I've seen the docs for the Router object but neither seems to be callback-based. In other words, when I transition to a new page, the WebGL and the page transitions run at the same time. And I don't want to do a hacky solution like adding a delay for the page transitions so they happen after the WebGL ones.
This is what I have right now:
app.js
<TransitionGroup>
<Transition
timeout={{ enter: 2000, exit: 2000 }}
// unmountOnExit={true}
onEnter={(node) => {
gsap.fromTo(node, { opacity: 0 }, { opacity: 1, duration: 1 });
}}
onExit={(node) => {
gsap.to(node, { opacity: 0, duration: 1 });
}}
key={router.route}
>
<Component {...pageProps}></Component>
</Transition>
</TransitionGroup>
webgl portion
Router.events.on('routeChangeStart', (url) => {
// transition webGL elements
// ideally would transition webGL elements and then allow callback to transition out html elements
});
I've also tried using the eventemitter3 library to do something like:
// a tag element click handler
onClick(e, href) {
e.preventDefault();
this.transitionOut().then(() => { Emitter.emit('push', href); });
// then we listen to Emitter 'push' event and that's when we Router.push(href)
}
However this method ran into huge issues when using the back / forward buttons for navigating
Bit late on this but I was looking into this myself today. It's really easy to use Framer Motion for this but I also wanted to use GSAP / React Transition Group.
For Framer Motion I just wrapped the Next < Component > with a motion component:
<motion.div
key={router.asPath}
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
>
<Component {...pageProps} />
</motion.div>
For GSAP / React Transition Group, not sure if this is the right way but it's working as intended for me (see comments):
const [state, setstate] = useState(router.asPath) // I set the current asPath as the state
useEffect(() => {
const handleStart = () => {
setstate(router.asPath) // then on a router change, I'm setting the state again
// other handleStart logic goes here
}
const handleStop = () => {
... // handleStop logic goes here
}
router.events.on("routeChangeStart", handleStart)
router.events.on("routeChangeComplete", handleStop)
router.events.on("routeChangeError", handleStop)
return () => {
router.events.off("routeChangeStart", handleStart)
router.events.off("routeChangeComplete", handleStop)
router.events.off("routeChangeError", handleStop)
}
}, [router])
<Transition
in={router.asPath !== state} // here I'm just checking if the state has changed, then triggering the animations
onEnter={enter => gsap.set(enter, { opacity: 0 })}
onEntered={entered => gsap.to(entered, { opacity: 1, duration: 0.3 })}
onExit={exit => gsap.to(exit, { opacity: 0, duration: 0.3 })}
timeout={300}
appear
>
<Component {...pageProps} />
</Transition>
First I recommend reading Greensock’s React documentation.
Intro Animations in Next.JS
For intro animations, if you use useLayoutEffect with SSR your console will fill up with warnings. To avoid this apply useIsomorphicLayoutEffect instead. Go to useIsomorphicLayoutEffect.
To prevent the flash of unstyled content (FOUC) with SSR, you need to set the initial styling state of the component. For example, if we are fading in, the initial style of that component should be an opacity of zero.
Outro Animations in Next.JS
For outro animations, intercept the page transition, and do the exit animations, then onComplete route to the next page.
To pull this off, we can use TransitionLayout higher order component as a wrapper to delay the routing change until after any animations have completed, and a TransitionProvider component that will take advantage of React’s useContext hook to share an outro timeline across multiple components, regardless of where they are nested.
Transition Context
In order to make a page transition effect, we need to prevent rendering the new page before our outro animation is done.
We may have many components with different animation effects nested in our pages. To keep track of all the different outro transitions, we will use a combination of React’s Context API and a top-level GSAP timeline.
In TransitionContext we will create our TransitionProvider which will make our GSAP timeline for outro animations available to any components who would like to transition out during a page change.
import React, { useState, createContext, useCallback } from "react"
import gsap from "gsap"
const TransitionContext = createContext({})
const TransitionProvider = ({ children }) => {
const [timeline, setTimeline] = useState(() =>
gsap.timeline({ paused: true })
)
return (
<TransitionContext.Provider
value={{
timeline,
setTimeline,
}}
>
{children}
</TransitionContext.Provider>
)
}
export { TransitionContext, TransitionProvider }
Next, we have TransitionLayout which will be our controller that will initiate the outro animations and update the page when they are all complete.
import { gsap } from "gsap"
import { TransitionContext } from "../context/TransitionContext"
import { useState, useContext, useRef } from "react"
import useIsomorphicLayoutEffect from "../animation/useIsomorphicLayoutEffect"
export default function TransitionLayout({ children }) {
const [displayChildren, setDisplayChildren] = useState(children)
const { timeline, background } = useContext(TransitionContext)
const el = useRef()
useIsomorphicLayoutEffect(() => {
if (children !== displayChildren) {
if (timeline.duration() === 0) {
// there are no outro animations, so immediately transition
setDisplayChildren(children)
} else {
timeline.play().then(() => {
// outro complete so reset to an empty paused timeline
timeline.seek(0).pause().clear()
setDisplayChildren(children)
})
}
}
}, [children])
return <div ref={el}>{displayChildren}</div>
}
In a custom App component, we can have TransitionProvider and TransitionLayout wrap the other elements so they can access the TransitionContext properties. Header and Footer exist outside of Component so that they will be static after the initial page load.
import { TransitionProvider } from "../src/context/TransitionContext"
import TransitionLayout from "../src/animation/TransitionLayout"
import { Box } from "theme-ui"
import Header from "../src/ui/Header"
import Footer from "../src/ui/Footer"
export default function MyApp({ Component, pageProps }) {
return (
<TransitionProvider>
<TransitionLayout>
<Box
sx={{
display: "flex",
minHeight: "100vh",
flexDirection: "column",
}}
>
<Header />
<Component {...pageProps} />
<Footer />
</Box>
</TransitionLayout>
</TransitionProvider>
)
}
Component-Level Animation
Here is an example of a basic animation we can do at the component level. We can add as many of these as we want to a page and they will all do the same thing, wrap all its children in a transparent div and fade it in on page load, then fade out when navigating to a different page.
import { useRef, useContext } from "react"
import { gsap } from "gsap"
import { Box } from "theme-ui"
import useIsomorphicLayoutEffect from "./useIsomorphicLayoutEffect"
import { TransitionContext } from "../context/TransitionContext"
const FadeInOut = ({ children }) => (
const { timeline } = useContext(TransitionContext)
const el = useRef()
// useIsomorphicLayoutEffect to avoid console warnings
useIsomorphicLayoutEffect(() => {
// intro animation will play immediately
gsap.to(el.current, {
opacity: 1,
duration: 1,
})
// add outro animation to top-level outro animation timeline
timeline.add(
gsap.to(el.current, {
opacity: 1,
duration: .5,
}),
0
)
}, [])
// set initial opacity to 0 to avoid FOUC for SSR
<Box ref={el} sx={{opacity: 0}}>
{children}
</Box>
)
export default FadeInOut
We can take this pattern and extract it into an extendable AnimateInOut helper component for reusable intro/outro animation patterns in our app.
import React, { useRef, useContext } from "react"
import { gsap } from "gsap"
import { Box } from "theme-ui"
import useIsomorphicLayoutEffect from "./useIsomorphicLayoutEffect"
import { TransitionContext } from "../context/TransitionContext"
const AnimateInOut = ({
children,
as,
from,
to,
durationIn,
durationOut,
delay,
delayOut,
set,
skipOutro,
}) => {
const { timeline } = useContext(TransitionContext)
const el = useRef()
useIsomorphicLayoutEffect(() => {
// intro animation
if (set) {
gsap.set(el.current, { ...set })
}
gsap.to(el.current, {
...to,
delay: delay || 0,
duration: durationIn,
})
// outro animation
if (!skipOutro) {
timeline.add(
gsap.to(el.current, {
...from,
delay: delayOut || 0,
duration: durationOut,
}),
0
)
}
}, [])
return (
<Box as={as} sx={from} ref={el}>
{children}
</Box>
)
}
export default AnimateInOut
The AnimateInOut component has built in flexibility for different scenarios:
Setting different animations, durations and delays for intros and outros
Skipping the outro
Setting the element tag for the wrapper, e.g. use a <span> instead of a <div>
Use GSAP’s set option to define initial values for the intro
Using this we can create all sorts of reusable intro/outro animations, such as <FlyInOut>, <ScaleInOut>, <RotateInOut3D> and so forth.
I have a demo project where you can see the above in practice: TweenPages

Moving slider with Cypress

I've got a Slider component from rc-slider and I need Cypress to set the value of it.
<Slider
min={5000}
max={40000}
step={500}
value={this.state.input.amount}
defaultValue={this.state.input.amount}
className="sliderBorrow"
onChange={(value) => this.updateInput("amount",value)}
data-cy={"input-slider"}
/>
This is my Cypress code:
it.only("Changing slider", () => {
cy.visit("/");
cy.get(".sliderBorrow")
.invoke("val", 23000)
.trigger("change")
.click({ force: true })
});
What I've tried so far does not work.
Starting point of slider is 20000, and after test runs it goes to 22000, no matter what value I pass, any number range.
Looks like it used to work before, How do interact correctly with a range input (slider) in Cypress? but not anymore.
The answer is very and very simple. I found the solution coincidentally pressing enter key for my another test(date picker) and realized that pressing left or right arrow keys works for slider.
You can achieve the same result using props as well. The only thing you need to do is to add this dependency: cypress-react-selector and following instructions here: cypress-react-selector
Example of using {rightarrow}
it("using arrow keys", () => {
cy.visit("localhost:3000");
const currentValue = 20000;
const targetValue = 35000;
const increment = 500;
const steps = (targetValue - currentValue) / increment;
const arrows = '{rightarrow}'.repeat(steps);
cy.get('.rc-slider-handle')
.should('have.attr', 'aria-valuenow', 20000)
.type(arrows)
cy.get('.rc-slider-handle')
.should('have.attr', 'aria-valuenow', 35000)
})
#darkseid's answer helped guide me reach an optimal solution.
There are two steps
Click the slider's circle, to move the current focus on the slider.
Press the keyboard arrow buttons to reach your desired value.
My slider jumps between values on the sliders, therefore this method would work. (I am using Ion range slider)
This method doesn't require any additional depedency.
// Move the focus to slider, by clicking on the slider's circle element
cy.get(".irs-handle.single").click({ multiple: true, force: true });
// Press right arrow two times
cy.get(".irs-handle.single").type(
"{rightarrow}{rightarrow}"
);
You might be able to tackle this using Application actions, provided you are able to modify the app source code slightly.
Application actions give the test a hook into the app that can be used to modify the internal state of the app.
I tested it with a Function component exposing setValue from the useState() hook.
You have used a Class component, so I guess you would expose this.updateInput() instead, something like
if (window.Cypress) {
window.app = { updateInput: this.updateInput };
}
App: index.js
import React, { useState } from 'react';
import { render } from 'react-dom';
import './style.css';
import Slider from 'rc-slider';
import 'rc-slider/assets/index.css';
function App() {
const [value, setValue] = useState(20000);
// Expose the setValue() method so that Cypress can set the app state
if (window.Cypress) {
window.app = { setValue };
}
return (
<div className="App">
<Slider
min={5000}
max={40000}
step={500}
value={value}
defaultValue={value}
className="sliderBorrow"
onChange={val => setValue(val)}
data-cy={"input-slider"}
/>
<div style={{ marginTop: 40 }}><b>Selected Value: </b>{value}</div>
</div>
);
}
render(<App />, document.getElementById('root'));
Test: slider.spec.js
The easiest way I found assert the value in the test is to use the aria-valuenow attribute of the slider handle, but you may have another way of testing that the value has visibly changed on the page.
describe('Slider', () => {
it("Changing slider", () => {
cy.visit("localhost:3000");
cy.get('.rc-slider-handle')
.should('have.attr', 'aria-valuenow', 20000)
cy.window().then(win => {
win.app.setValue(35000);
})
cy.get('.rc-slider-handle')
.should('have.attr', 'aria-valuenow', 35000)
})
})
For whoever comes across this with Material UI/MUI 5+ Sliders:
First off, this github issue and comment might be useful: https://github.com/cypress-io/cypress/issues/1570#issuecomment-606445818.
I tried changing the value by accessing the input with type range that is used underneath in the slider, but for me that did not do the trick.
My solution with MUI 5+ Slider:
<Slider
disabled={false}
step={5}
marks
data-cy="control-percentage"
name="control-percentage"
defaultValue={0}
onChange={(event, newValue) =>
//Handle change
}
/>
What is important here is the enabled marks property. This allowed me to just click straight on the marks in the cypress test, which of course can also be abstracted to a support function.
cy.get('[data-cy=control-percentage]').within(() => {
// index 11 represents 55 in this case, depending on your step setting.
cy.get('span[data-index=11]').click();
});
I got this to work with the popular react-easy-swipe:
cy.get('[data-cy=week-picker-swipe-container]')
.trigger('touchstart', {
touches: [{ pageY: 0, pageX: 0 }]
})
.trigger('touchmove', {
touches: [{ pageY: 0, pageX: -30 }]
})

Resources