### Basic useVelocity Example
Source: https://motion.dev/docs/react-use-velocity
This example demonstrates how to use useVelocity to get the velocity of a motion value and then use that velocity to transform the scale of a motion component. It requires importing useMotionValue and useVelocity.
```jsx
const x = useMotionValue(0)
const xVelocity = useVelocity(x)
const scale = useTransform(
xVelocity,
[-3000, 0, 3000],
[2, 1, 2],
{ clamp: false }
)
return
```
--------------------------------
### Install Motion+ Package
Source: https://motion.dev/docs/react-scramble-text
Install the motion-plus package using npm. Ensure you have your Motion+ private token to access the registry.
```bash
npm install "https://api.motion.dev/registry.tgz?package=motion-plus&version=2.6.1&token=YOUR_AUTH_TOKEN"
```
--------------------------------
### Install Motion with npm
Source: https://motion.dev/docs/react-installation
Use npm to install the Motion package in your React project.
```bash
npm install motion
```
--------------------------------
### Install Motion with pnpm
Source: https://motion.dev/docs/react-installation
Use pnpm to install the Motion package in your React project.
```bash
pnpm add motion
```
--------------------------------
### Full Example with State and startTransition
Source: https://motion.dev/docs/react-animate-view
A complete React component example showing state management with useState and triggering animations using startTransition and AnimateView.
```jsx
import { AnimateView } from "motion-plus/animate-view"
import { startTransition, useState } from "react"
function Example() {
const [show, setShow] = useState(true)
return (
<>
{show && (
)}
>
)
}
```
--------------------------------
### Install Motion Plus Package
Source: https://motion.dev/docs/react-typewriter
Install the motion-plus package using npm with your private authentication token. Ensure you are a Motion+ member to obtain a token.
```bash
npm install "https://api.motion.dev/registry.tgz?package=motion-plus&version=2.8.0&token=YOUR_AUTH_TOKEN"
```
--------------------------------
### Install Motion+ Ticker
Source: https://motion.dev/docs/react-ticker
Install the motion-plus package using npm with your private authentication token. Ensure you are a Motion+ member to obtain a token.
```bash
npm install "https://api.motion.dev/registry.tgz?package=motion-plus&version=2.0.2&token=YOUR_AUTH_TOKEN"
```
--------------------------------
### Install Carousel Component
Source: https://motion.dev/docs/react-carousel
Install the motion-plus package using npm. Ensure you have a Motion+ membership to generate a private token.
```bash
npm install "https://api.motion.dev/registry.tgz?package=motion-plus&version=2.11.0&token=YOUR_AUTH_TOKEN"
```
--------------------------------
### Install Motion+ Package
Source: https://motion.dev/docs/react-animate-number
Install the motion-plus package for React using npm. Ensure you replace YOUR_AUTH_TOKEN with your actual Motion+ private token.
```bash
npm install "https://api.motion.dev/registry.tgz?package=motion-plus&version=2.10.0&token=YOUR_AUTH_TOKEN"
```
--------------------------------
### Uninstall framer-motion and install motion
Source: https://motion.dev/docs/react-upgrade-guide
To upgrade to Motion for React, uninstall the old package and install the new one.
```bash
npm uninstall framer-motion
npm install motion
```
--------------------------------
### Install Motion with Yarn
Source: https://motion.dev/docs/react-installation
Use Yarn to add the Motion package to your React project.
```bash
yarn add motion
```
--------------------------------
### Import Motion components in React
Source: https://motion.dev/docs/react-installation
After installation, import Motion's components and hooks from 'motion/react'.
```javascript
import { motion } from "motion/react"
```
--------------------------------
### useTransform clamp option example
Source: https://motion.dev/docs/react-use-transform
Compares the behavior of useTransform with clamp set to true (default) and false, showing how output is constrained or continues to map outside the input range.
```javascript
const y = useTransform(x, [0, 1], [0, 2])
const z = useTransform(x, [0, 1], [0, 2], { clamp: false })
useEffect(() => {
x.set(2)
console.log(y.get()) // 2, input clamped
console.log(z.get()) // 4
})
```
--------------------------------
### Basic Reduced Motion Check
Source: https://motion.dev/docs/react-use-reduced-motion
A simple example demonstrating how to get the boolean value from the useReducedMotion hook.
```javascript
const shouldReduceMotion = useReducedMotion()
```
--------------------------------
### Using useVelocity with useMotionValueEvent
Source: https://motion.dev/docs/react-use-velocity
This example shows how to use useVelocity in conjunction with useMotionValueEvent to log the velocity of a motion value whenever it changes. It requires importing useMotionValue, useVelocity, and useMotionValueEvent.
```jsx
import { useMotionValue, useVelocity } from "framer-motion"
function Component() {
const x = useMotionValue(0)
const xVelocity = useVelocity(x)
useMotionValueEvent(xVelocity, "change", latest => {
console.log("Velocity", latestVelocity)
})
return
}
```
--------------------------------
### CSS Transition Example
Source: https://motion.dev/docs/react-motion-config
This CSS demonstrates a transition for the 'scale' property, with a custom ease curve defined using linear interpolation. It's used in conjunction with Motion for visual editing.
```css
1.card {
transition: scale 200ms linear(3 0, 0.009, 0.036, 0.084, 0.157, 0.255, 0.378,
0.522, 0.679, 0.832, 0.954, 1.029, 1.052, 1.038,
1.011, 0.99, 0.984, 0.991, 1.001, 1.005, 1
);
}
.card:hover {
scale: 1.2;
}
```
--------------------------------
### Layout Animation with Initial Border Radius
Source: https://motion.dev/docs/react-upgrade-guide
Example of using `layout` prop with `initial` to animate `borderRadius` in Framer Motion 2.0, fixing potential distortions.
```javascript
```
--------------------------------
### Transform function example with time-based animation
Source: https://motion.dev/docs/react-use-transform
Creates a motion value 'y' that animates based on the sine wave of time, demonstrating dynamic transformations.
```javascript
const distance = 100
const time = useTime()
const y = useTransform(() => Math.sin(time.get() / 1000) * distance)
```
--------------------------------
### Get Motion Value State
Source: https://motion.dev/docs/react-motion-value
Illustrates how to retrieve the current state of a motion value using the `get` method.
```javascript
x.get() // 100
```
--------------------------------
### Set Motion Value to Color
Source: https://motion.dev/docs/react-motion-value
Example of using the `set` method to update a motion value with a string value, such as a color.
```javascript
x.set("#f00")
```
--------------------------------
### useInView with Margin Option
Source: https://motion.dev/docs/react-use-in-view
This example demonstrates the use of the 'margin' option to expand or shrink the detection area around the viewport. It allows for more precise control over when an element is considered 'in view'.
```jsx
const isInView = useInView(ref, {
margin: "0px 100px -50px 0px"
})
```
--------------------------------
### Dynamic Enter Animation with Transition Types
Source: https://motion.dev/docs/react-animate-view
An example of a dynamic enter animation for AnimateView that resolves based on the provided transition types, allowing for conditional transforms.
```jsx
({
transform: [
`translateX(${types.includes("next") ? 100 : -100}%)`,
"none",
],
})}>
```
--------------------------------
### Dynamic Enter and Exit Animations based on Transition Types
Source: https://motion.dev/docs/react-animate-view
This example shows how to define dynamic enter and exit animations for AnimateView that adapt based on the transition types provided by addTransitionType.
```jsx
({
transform: `translateX(${types.includes("prev") ? 100 : -100}%)`,
})}
enter={(types) => ({
transform: [
`translateX(${types.includes("next") ? 100 : -100}%)`,
"translateX(0%)",
],
})}>
```
--------------------------------
### Mapping single motion value to multiple named output values
Source: https://motion.dev/docs/react-use-transform
An alternative to the previous example, this maps a single motion value to multiple named output properties (opacity, scale, filter) in one call.
```javascript
const { opacity, scale, filter } = useTransform(offset, [100, 600], {
opacity: [1, 0.4],
scale: [1, 0.6],
filter: ["blur(0px)", "blur(10px)"],
})
```
--------------------------------
### Start Drag from Another Element
Source: https://motion.dev/docs/react-use-drag-controls
Initiate a drag gesture from a separate element's pointer down event using the controls.
```javascript
controls.start(event)} />
```
--------------------------------
### Compose Motion Values with useTransform
Source: https://motion.dev/docs/react-motion-value
Example of composing motion values where a new motion value `y` is derived from the current value of `x` multiplied by two.
```javascript
const y = useTransform(() => x.get() * 2)
```
--------------------------------
### Motion Value Methods
Source: https://motion.dev/docs/react-motion-value
Provides methods to interact with motion values, including getting their state and velocity, setting new states, and managing animations.
```APIDOC
## Motion Value API
### `get()`
Returns the latest state of the motion value.
### `getVelocity()`
Returns the latest velocity of the motion value. Returns `0` if the value is non-numerical.
### `set(state)`
Sets the motion value to a new state. This updates the DOM without triggering a React re-render.
```javascript
x.set(100)
```
### `jump(state)`
Jumps the motion value to a new state, resetting velocity and ending active animations.
```javascript
x.jump(10)
```
### `isAnimating()`
Returns `true` if the value is currently animating.
### `stop()`
Stops the active animation of the motion value.
### `on(event, listener)`
Subscribes to motion value events. Available events are: `change`, `animationStart`, `animationCancel`, `animationComplete`.
Returns a function that unsubscribes the listener.
```javascript
const unsubscribe = x.on("change", latest => console.log(latest))
```
```
--------------------------------
### Lightweight Hover Gesture Recognition with hover()
Source: https://motion.dev/docs/react-hover-animation
For efficient hover gesture handling, import the `hover()` function from 'motion'. This function can be integrated with `useEffect` to manage hover start and end callbacks, returning a cleanup function for proper unsubscription.
```javascript
import { hover } from "motion"
import { useRef, useEffect } from "react"
function Component() {
const ref = useRef(null)
useEffect(() => {
return hover(ref.current, () => {
console.log("on hover start")
return () => console.log("on hover end")
})
}, [])
return
}
```
--------------------------------
### useEffect with useInView
Source: https://motion.dev/docs/react-use-in-view
This example shows how to trigger side effects based on the visibility state returned by useInView. It utilizes the useEffect hook to log a message whenever the isInView state changes.
```jsx
useEffect(() => {
console.log("Element is in view: ", isInView)
}, [isInView])
```
--------------------------------
### Jest test for synchronous render scheduling (pre-11.0)
Source: https://motion.dev/docs/react-upgrade-guide
This example shows a Jest test that assumes synchronous render updates, which was the behavior before version 11.0.
```javascript
render(
)
expect(element).toHaveStyle("opacity: 1")
```
--------------------------------
### Hover Start and End Event Handlers
Source: https://motion.dev/docs/react-hover-animation
Utilize `onHoverStart` and `onHoverEnd` event handlers to execute functions when a hover gesture begins and concludes. These events are designed to fire only on devices where hover is genuinely possible, filtering out touch events.
```jsx
console.log('Hover starts')}
onHoverEnd={() => console.log('Hover ends')}
/>
```
--------------------------------
### Set Default Transition with MotionConfig
Source: https://motion.dev/docs/react-motion-config
Use MotionConfig to define a fallback transition for all child motion components. This example sets a default duration of 1 second for all animations.
```jsx
import { motion, MotionConfig } from "motion/react"
export const MyComponent = ({ isVisible }) => (
)
```
--------------------------------
### Control Animation Loops with Page Visibility
Source: https://motion.dev/docs/react-use-page-in-view
Conditionally start or stop animation loops created with useAnimationFrame based on the page's visibility state.
```javascript
useAnimationFrame(isPageInView ? update : undefined)
```
--------------------------------
### Animating Updates with AnimateView
Source: https://motion.dev/docs/react-animate-view
Animate elements when their content or styles change using the 'update' prop. This example shows animating background color changes.
```jsx
```
--------------------------------
### Basic useAnimate Hook Usage
Source: https://motion.dev/docs/react-use-animate
This example demonstrates the fundamental usage of the useAnimate hook. The 'li' selector is scoped to the element with the 'scope' ref, ensuring animations only affect children of that element. Animations are triggered within a useEffect hook.
```jsx
function Component() {
const [scope, animate] = useAnimate()
useEffect(() => {
// This "li" selector will only select children
// of the element that receives `scope`.
animate("li", { opacity: 1 })
})
return
{children}
}
```
--------------------------------
### Jest test for asynchronous render scheduling (11.0+)
Source: https://motion.dev/docs/react-upgrade-guide
Tests for version 11.0+ should await an animation frame due to changes in render scheduling. This example demonstrates the updated testing approach.
```javascript
render(
)
await nextFrame()
expect(element).toHaveStyle("opacity: 1")
// utils.js
import { frame } from "framer-motion"
export async function nextFrame() {
return new Promise((resolve) => {
frame.postRender(() => resolve())
})
}
```
--------------------------------
### Get Page Visibility State
Source: https://motion.dev/docs/react-use-page-in-view
Call the usePageInView hook to get a boolean indicating if the page is currently in view.
```javascript
const isPageInView = usePageInView()
```
--------------------------------
### Configure Spring Transition Options
Source: https://motion.dev/docs/react-use-spring
Define the spring's stiffness and other transition properties when creating a useSpring motion value.
```javascript
useSpring(0, { stiffness: 300 })
```
--------------------------------
### Importing useAnimate Hook
Source: https://motion.dev/docs/react-use-animate
Shows how to import the useAnimate hook from the Motion library. Choose the 'mini' or 'react' import based on your project's needs.
```javascript
// Mini
import { useAnimate } from "motion/react-mini"
// Hybrid
import { useAnimate } from "motion/react"
```
--------------------------------
### Triggering View Transitions with startTransition
Source: https://motion.dev/docs/react-animate-view
Demonstrates how to use React's startTransition to wrap state updates that trigger AnimateView's enter/exit animations.
```jsx
startTransition(() => setShow(!show))
```
--------------------------------
### Basic useInView Usage
Source: https://motion.dev/docs/react-use-in-view
This snippet demonstrates the fundamental usage of the useInView hook. It requires importing useRef and useInView, and then passing a ref object to both the hook and the target HTML element.
```jsx
const ref = useRef(null)
const isInView = useInView(ref)
return
```
```jsx
import { useInView } from "motion/react"
function Component() {
const ref = useRef(null)
const isInView = useInView(ref)
return
}
```
--------------------------------
### Disable Automatic Drag Listener
Source: https://motion.dev/docs/react-use-drag-controls
Prevent the motion component from automatically starting a drag gesture on pointerdown by setting dragListener to false.
```javascript
```
--------------------------------
### ScrambleText with Stagger Direction
Source: https://motion.dev/docs/react-scramble-text
Customize the direction of the stagger animation by using the 'from' option within the stagger function, such as starting from the center.
```jsx
Hello world!
```
--------------------------------
### Basic useTime Animation
Source: https://motion.dev/docs/react-use-time
Demonstrates how to use useTime with useTransform to create a perpetual rotation animation. The animation runs indefinitely and is not clamped.
```jsx
const time = useTime();
const rotate = useTransform(time, [0, 4000], [0, 360], { clamp: false });
return ;
```
--------------------------------
### Compose Motion Values with useSpring
Source: https://motion.dev/docs/react-motion-value
Illustrates creating spring-based motion values for `x` and `y` that are driven by separate motion values `dragX` and `dragY`.
```javascript
const dragX = useMotionValue(0)
const dragY = useMotionValue(0)
const x = useSpring(dragX)
const y = useSpring(dragY)
```
--------------------------------
### Basic useTransform with addition
Source: https://motion.dev/docs/react-use-transform
Demonstrates creating a new motion value 'z' by summing two existing motion values 'x' and 'y' using a transform function.
```javascript
const x = useMotionValue(1)
const y = useMotionValue(1)
const z = useTransform(() => x.get() + y.get()) // z.get() === 2
```
--------------------------------
### Layout Animation with Default Transition in Framer Motion 2 (After)
Source: https://motion.dev/docs/react-upgrade-guide
Shows how to apply layout animations with a default `transition` prop in Framer Motion 2.0 and later.
```javascript
// After
```
--------------------------------
### AnimateView with Spring Transition Configuration
Source: https://motion.dev/docs/react-animate-view
Shows how to apply a spring transition to an AnimateView component, specifying visual duration and bounce.
```jsx
```
--------------------------------
### ScrambleText with Stagger Duration
Source: https://motion.dev/docs/react-scramble-text
Implement a letter-by-letter reveal effect by using Motion's stagger function for the duration. This controls when each character starts scrambling.
```jsx
import { stagger } from "motion"
import { StaggerText } from "motion-plus/react"
// Start scrambling at the same time, reveal after 1
// second, with a 0.05 delay between each character/
Hello world!
```
--------------------------------
### Get Motion Value Velocity
Source: https://motion.dev/docs/react-motion-value
Shows how to obtain the current velocity of a numerical motion value using `getVelocity`. This method accounts for frame rate variations.
```javascript
const xVelocity = x.getVelocity()
```
--------------------------------
### Layout Animations in Framer Motion 2 (After)
Source: https://motion.dev/docs/react-upgrade-guide
Demonstrates the use of the `layout` prop for layout animations in Framer Motion 2.0 and later.
```javascript
// After
```
--------------------------------
### useTransform with transform function and value mapping
Source: https://motion.dev/docs/react-use-transform
Illustrates the two primary ways to use useTransform: with a transform function for calculations and with value mapping for range transformations.
```javascript
// Transform function
const doubledX = useTransform(() => x.get() * 2)
// Value mapping
const color = useTransform(x, [0, 100], ["#f00", "#00f"])
```
--------------------------------
### Enable Touch Support
Source: https://motion.dev/docs/react-use-drag-controls
Apply touch-action: none to the triggering element for proper touch screen support.
```javascript
```
--------------------------------
### Velocity calculation in previous versions
Source: https://motion.dev/docs/react-upgrade-guide
In older versions, multiple MotionValue updates within the same animation frame affected velocity calculations. This example shows the previous behavior.
```javascript
const x = motionValue(0)
requestAnimationFrame(() => {
x.set(100)
x.getVelocity() // Velocity of 0 -> 100
x.set(200)
x.getVelocity() // Velocity of 100 -> 200
})
```
--------------------------------
### Basic useMotionTemplate
Source: https://motion.dev/docs/react-use-motion-template
Combines a motion value with static text to create a new motion value representing a CSS transform. Import useMotionValue and useMotionTemplate from 'motion/react'.
```javascript
import { useMotionValue, useMotionTemplate } from "motion/react"
const x = useMotionValue(100)
const transform = useMotionTemplate`transform(${x}px)`
```
--------------------------------
### Velocity calculation in version 11+
Source: https://motion.dev/docs/react-upgrade-guide
From version 11, subsequent MotionValue updates within synchronous code blocks do not affect velocity calculations. This example demonstrates the corrected behavior.
```javascript
const x = motionValue(0)
requestAnimationFrame(() => {
x.set(100)
x.getVelocity() // Velocity of 0 -> 100
x.set(200)
x.getVelocity() // Velocity of 0 -> 200
})
```
--------------------------------
### Mapping single motion value to multiple output values
Source: https://motion.dev/docs/react-use-transform
Shows how to create multiple motion values (opacity, scale, filter) from a single input motion value and range.
```javascript
const opacity = useTransform(offset, [100, 600], [1, 0.4])
const scale = useTransform(offset, [100, 600], [1, 0.6])
const filter = useTransform(offset, [100, 600], ["blur(0px)", "blur(10px)"])
```
--------------------------------
### Basic AnimateView Usage
Source: https://motion.dev/docs/react-animate-view
Demonstrates the basic usage of AnimateView to wrap a modal that appears and disappears.
```jsx
isOpen && (
)
```
--------------------------------
### Value mapping with input and output ranges
Source: https://motion.dev/docs/react-use-transform
Maps a motion value 'x' from an input range [-100, 0, 100] to an output range [0, 1, 0] for opacity.
```javascript
const input = [-100, 0, 100]
const output = [0, 1, 0]
```
--------------------------------
### useInView with Initial Option
Source: https://motion.dev/docs/react-use-in-view
This option sets an initial boolean value that useInView will return before the element's visibility has been measured. This can be useful for controlling the initial render state.
```jsx
const isInView = useInView(ref, { initial: true })
```
--------------------------------
### Configure Specific Enter Transition
Source: https://motion.dev/docs/react-animate-view
Configure a specific transition for the 'enter' animation using the 'enter' prop with a 'transition' object. Note that 'spring' must be imported from 'motion'.
```jsx
```
--------------------------------
### Import useSpring
Source: https://motion.dev/docs/react-use-spring
Import the useSpring hook from the Motion React library.
```javascript
import { useSpring } from "motion/react"
```
--------------------------------
### Import usePageInView Hook
Source: https://motion.dev/docs/react-use-page-in-view
Import the usePageInView hook from the motion/react library.
```javascript
import { usePageInView } from "motion/react"
```
--------------------------------
### Initialize and Assign Drag Controls
Source: https://motion.dev/docs/react-use-drag-controls
Initialize drag controls and pass them to a draggable motion component.
```javascript
const controls = useDragControls()
return
```
--------------------------------
### Configuring AnimateView Transition Duration
Source: https://motion.dev/docs/react-animate-view
Shows how to configure the transition duration for an AnimateView component using the 'transition' prop.
```jsx
```
--------------------------------
### Nested Layout Animations for Child Components
Source: https://motion.dev/docs/react-upgrade-guide
Demonstrates how to apply the `layout` prop to child components to correct scaling distortions caused by parent layout animations.
```javascript
```
--------------------------------
### Customizing Hover Animation Transitions
Source: https://motion.dev/docs/react-hover-animation
Define custom transition properties for when a hover gesture starts by nesting a `transition` object within the `whileHover` definition. The `transition` prop at the component level controls the animation when the hover gesture ends.
```jsx
```
--------------------------------
### Add Motion via CDN
Source: https://motion.dev/docs/react-installation
Import Motion directly from a CDN using a script tag with type module.
```html
```
--------------------------------
### Subscribe to Motion Value Events with on()
Source: https://motion.dev/docs/react-motion-value
Shows how to subscribe to motion value events using the `on` method. The returned function can be called to unsubscribe the listener.
```javascript
const unsubscribe = x.on("change", latest => console.log(latest))
```
--------------------------------
### Layout Transition with Duration in Framer Motion 2 (Before)
Source: https://motion.dev/docs/react-upgrade-guide
Illustrates passing a transition object to `layoutTransition` before Framer Motion 2.0.
```javascript
// Before
```
--------------------------------
### Initialize a Motion Value
Source: https://motion.dev/docs/react-motion-value
Illustrates the basic usage of the `useMotionValue` hook to create a motion value with an initial state.
```jsx
import { useMotionValue } from "motion/react"
const x = useMotionValue(0)
```
--------------------------------
### Importing useVelocity
Source: https://motion.dev/docs/react-use-velocity
To use the useVelocity hook, import it from the 'motion/react' library.
```javascript
import { useVelocity } from "motion/react"
```
--------------------------------
### Import AnimateView
Source: https://motion.dev/docs/react-animate-view
Import the AnimateView component from the 'motion-plus/animate-view' module.
```jsx
import { AnimateView } from "motion-plus/animate-view"
```
--------------------------------
### Basic useMotionValueEvent Usage
Source: https://motion.dev/docs/react-use-motion-value-event
Listen for 'animationStart' and 'change' events on a motion value 'x'. Event handlers are automatically cleaned up on component unmount.
```jsx
function Component() {
const x = useMotionValue(0)
useMotionValueEvent(x, "animationStart", () => {
console.log("animation started on x")
})
useMotionValueEvent(x, "change", (latest) => {
console.log("x changed to", latest)
})
return
}
```
--------------------------------
### Exit Animations with usePresence
Source: https://motion.dev/docs/react-use-animate
Demonstrates creating custom exit animations using useAnimate in conjunction with usePresence. The useEffect hook manages enter and exit animations, calling safeToRemove when the exit animation is complete.
```jsx
import { useAnimate, usePresence } from "framer-motion"
function Component() {
const [isPresent, safeToRemove] = usePresence()
const [scope, animate] = useAnimate()
useEffect(() => {
if (isPresent) {
const enterAnimation = async () => {
await animate(scope.current, { opacity: 1 })
await animate("li", { opacity: 1, x: 0 })
}
enterAnimation()
} else {
const exitAnimation = async () => {
await animate("li", { opacity: 0, x: -100 })
await animate(scope.current, { opacity: 0 })
safeToRemove()
}
exitAnimation()
}
}, [isPresent])
return (
)
}
```
--------------------------------
### Configure Default Transition
Source: https://motion.dev/docs/react-animate-view
Set a default transition for all view transitions using the 'transition' prop on AnimateView. Accepts all Motion's transition options.
```jsx
```
--------------------------------
### useInView with Amount Option
Source: https://motion.dev/docs/react-use-in-view
This option specifies the threshold for how much of an element must be visible in the viewport to be considered 'entered'. It accepts 'some', 'all', or a numerical value between 0 and 1.
```jsx
const isInView = useInView(ref, { amount: "all" })
```
--------------------------------
### AnimateView with Suspense for Fallback Content
Source: https://motion.dev/docs/react-animate-view
Demonstrates integrating AnimateView with Suspense to create crossfades between content and a fallback UI.
```jsx
}>
```
--------------------------------
### Import useTime Hook
Source: https://motion.dev/docs/react-use-time
Shows the correct import statement for the useTime hook from the motion/react library.
```javascript
import { useTime } from "motion/react"
```
--------------------------------
### Perpetual mapping with clamp: false
Source: https://motion.dev/docs/react-use-transform
Demonstrates how to use clamp: false to allow a motion value to map perpetually outside the defined input range, like rotating an element based on scroll.
```javascript
const { scrollY } = useScroll()
const rotate = useTransform(
scrollY,
[0, 100],
[0, 360],
{ clamp: false }
)
```
--------------------------------
### useInView with Once Option
Source: https://motion.dev/docs/react-use-in-view
This configuration of useInView ensures that the element is only observed until it enters the viewport for the first time. After that, it will always return true, preventing further re-renders related to visibility.
```jsx
const isInView = useInView(ref, { once: true })
```
--------------------------------
### Import useMotionValueEvent
Source: https://motion.dev/docs/react-use-motion-value-event
Import the useMotionValueEvent hook from the motion/react package.
```javascript
import { useMotionValueEvent } from "motion/react"
```
--------------------------------
### Lazy Load DOM Animations
Source: https://motion.dev/docs/react-reduce-bundle-size
Defer the loading of animations and interactions until after the initial site render by using a dynamic import function with `LazyMotion`. This approach significantly reduces the initial bundle size.
```javascript
// features.js
import { domMax } from "motion/react"
export default domMax
```
```javascript
import { LazyMotion } from "motion/react"
import * as m from "motion/react-m"
// Make sure to return the specific export containing the feature bundle.
const loadFeatures = () =>
import("./features.js").then(res => res.default)
// This animation will run when loadFeatures resolves.
function App() {
return (
)
}
```
--------------------------------
### useSpring Hook
Source: https://motion.dev/docs/react-motion-value
Creates a motion value that animates to its target value using a spring physics simulation.
```APIDOC
## `useSpring(initialValue)`
### Description
Creates a motion value that animates to its target value using spring physics. This is useful for creating natural-feeling animations.
### Usage
```javascript
const x = useSpring(dragX)
```
```
--------------------------------
### Create and Use a Motion Value
Source: https://motion.dev/docs/react-motion-value
Demonstrates creating a motion value `x` and applying it to a motion component's style. Motion values update the DOM without triggering React re-renders.
```jsx
import { motion, useMotionValue } from "motion/react"
export function MyComponent() {
const x = useMotionValue(0)
return
}
```
--------------------------------
### Basic Item Component with Layout Animation
Source: https://motion.dev/docs/react-layout-group
This component uses the `layout` prop for smooth transitions when its state changes. It also animates its header.
```jsx
function Item({
header,
content
}) {
const [isOpen, setIsOpen] = useState(false)
return (
setIsOpen(!isOpen)}
>
{header}
{isOpen ? content : null}
)
}
```
--------------------------------
### Basic useAnimationFrame Usage
Source: https://motion.dev/docs/react-use-animation-frame
Runs a callback function every animation frame, utilizing the total elapsed time.
```javascript
useAnimationFrame((time) => {
ref.current.style.transform = `rotateY(${time}deg)`
})
```
--------------------------------
### Layout Animations in Framer Motion 2 (Before)
Source: https://motion.dev/docs/react-upgrade-guide
Shows the usage of `layoutTransition` prop for layout animations in Framer Motion versions prior to 2.0.
```javascript
// Before
```
--------------------------------
### Create and Set a Spring Motion Value
Source: https://motion.dev/docs/react-use-spring
Initialize a spring motion value with a number and update its target using the .set() method.
```javascript
const x = useSpring(0)
x.set(100)
```
--------------------------------
### useMotionTemplate with multiple motion values
Source: https://motion.dev/docs/react-use-motion-template
Creates a CSS filter string by interpolating multiple motion values and static text. The returned motion value updates as 'saturate' changes. Import useMotionValue and useMotionTemplate from 'motion/react'.
```javascript
import { useMotionValue, useMotionTemplate } from "motion/react"
const blur = useMotionValue(10)
const saturate = useMotionValue(50)
const filter = useMotionTemplate`blur(${10}px) saturate(${saturate}%)`
return
```
--------------------------------
### Synchronously Load DOM Animations
Source: https://motion.dev/docs/react-reduce-bundle-size
Use `LazyMotion` with the `domAnimation` feature package to bundle DOM animations, variants, exit animations, and tap/hover/focus gestures into your main JavaScript bundle.
```javascript
import { LazyMotion, domAnimation } from "motion/react"
function App({ children }) {
return (
{children}
)
}
```
--------------------------------
### Import Slimmer 'm' Component
Source: https://motion.dev/docs/react-reduce-bundle-size
Instead of importing the full `motion` component, import the slimmer `m` component from `motion/react-m`. This component is used identically to `motion` but does not include preloaded features.
```javascript
import * as m from "motion/react-m"
```
--------------------------------
### useMotionTemplate for drop-shadow
Source: https://motion.dev/docs/react-use-motion-template
Generates a CSS drop-shadow string using two motion values and static text. The 'filter' motion value will update when 'shadowX' or 'shadowY' change. Import useSpring, useMotionValue, and useMotionTemplate from 'motion/react'.
```javascript
import { useSpring, useMotionValue, useMotionTemplate } from "motion/react"
const shadowX = useSpring(0)
const shadowY = useMotionValue(0)
const filter = useMotionTemplate`drop-shadow(${shadowX}px ${shadowY}px 20px rgba(0,0,0,0.3))`
return
```
--------------------------------
### Import useTransform from Motion
Source: https://motion.dev/docs/react-use-transform
Shows the correct import statement for using the useTransform hook in a React component.
```javascript
import { useTransform } from "motion/react"
```
--------------------------------
### Basic Ticker Usage
Source: https://motion.dev/docs/react-ticker
Use the Ticker component with a list of items to create a basic infinitely-scrolling ticker.
```jsx
```
--------------------------------
### useInView with Root Option
Source: https://motion.dev/docs/react-use-in-view
This snippet illustrates how to use the 'root' option with useInView to track visibility within a specific scrollable parent element instead of the window viewport. This is useful for components like carousels.
```jsx
function Carousel() {
const container = useRef(null)
const ref = useRef(null)
const isInView = useInView(ref, { root: container })
return (
)
}
```
--------------------------------
### Transform Motion Value for Style
Source: https://motion.dev/docs/react-motion-value
Shows how to use `useTransform` to create a new motion value (opacity) based on the range and output of another motion value (`x`). This is useful for synchronizing visual properties with motion.
```jsx
const x = useMotionValue(0)
const opacity = useTransform(
x,
[-200, 0, 200],
[0, 1, 0]
)
// Will change opacity as element is dragged left/right
return
```
--------------------------------
### Skip Initial Animation with useScroll
Source: https://motion.dev/docs/react-use-spring
When tracking a motion value that might change on mount (like useScroll), set skipInitialAnimation to true to jump to the initial value instantly.
```javascript
const { scrollYProgress } = useScroll()
const smoothProgress = useSpring(scrollYProgress, {
skipInitialAnimation: true,
})
```
--------------------------------
### Create and Set a Unit-Type Spring Motion Value
Source: https://motion.dev/docs/react-use-spring
Initialize a spring motion value with a unit-type string and update its target using the .set() method.
```javascript
const y = useSpring("100vh")
y.set("50vh")
```
--------------------------------
### Next.js App Router Optimized Import
Source: https://motion.dev/docs/react-installation
For reduced client-side JavaScript, replace the standard import with 'motion/react-client' in Next.js App Router projects.
```javascript
import * as motion from "motion/react-client"
export default function MyComponent() {
return
}
```
--------------------------------
### Import useDragControls
Source: https://motion.dev/docs/react-use-drag-controls
Import the useDragControls hook from the Motion library for React.
```javascript
import { useDragControls } from "motion/react"
```
--------------------------------
### Snap to Cursor
Source: https://motion.dev/docs/react-use-drag-controls
Make the motion component snap to the cursor during a drag gesture by passing snapToCursor: true.
```javascript
controls.start(event, { snapToCursor: true })
```
--------------------------------
### Async Loading Features with LazyMotion
Source: https://motion.dev/docs/react-lazy-motion
Asynchronously load animation features to ensure the site hydrates before loading animations. This improves initial page load performance.
```jsx
// features.js
import { domAnimation } from "motion/react"
export default domAnimation
// index.js
const loadFeatures = () => import("./features.js")
.then(res => res.default)
function Component() {
return (
)
}
```
--------------------------------
### Tab Component with Motion Div
Source: https://motion.dev/docs/react-animate-activity
A simple Tab component using motion.div with initial, animate, and exit opacity states for animation.
```jsx
function Tab() {
return (
)
}
```
--------------------------------
### useTransform ease option with cubicBezier
Source: https://motion.dev/docs/react-use-transform
Applies a custom cubic bezier easing function to the transformation between output values.
```javascript
const z = useTransform(
x,
[0, 1],
[0, 2],
{ ease: cubicBezier(0.17, 0.67, 0.83, 0.67) }
)
```
--------------------------------
### Check Reduced Motion Setting
Source: https://motion.dev/docs/react-use-reduced-motion
Import and call useReducedMotion to determine if the device's Reduced Motion setting is enabled.
```javascript
import { useReducedMotion } from "motion/react"
const prefersReducedMotion = useReducedMotion()
```
--------------------------------
### Composing useTime with useTransform
Source: https://motion.dev/docs/react-use-time
Illustrates composing the useTime motion value with useTransform to map elapsed time to a rotation range. The animation rotates 360 degrees over 4 seconds and repeats.
```jsx
const time = useTime()
const rotate = useTransform(
time,
[0, 4000], // For every 4 seconds...
[0, 360], // ...rotate 360deg
{ clamp: false }
)
```
--------------------------------
### Basic Hover Animation with whileHover
Source: https://motion.dev/docs/react-hover-animation
Use the `whileHover` prop on a `motion` component to declaratively define a target animation state for hover interactions. The component animates to these values on hover and returns to its previous state when the hover ends.
```jsx
```
--------------------------------
### AnimateView for Shared Element Animations
Source: https://motion.dev/docs/react-animate-view
Demonstrates the basic usage of AnimateView for shared element animations. Elements with the same 'name' prop will animate between states.
```jsx
function Item({ setSelectedItem }) {
return (
startTransition(() => setSelectedItem("item-1"))}
/>
)
}
function Modal({ selectedItem }) {
return (
)
}
```
--------------------------------
### useAnimationFrame with Time and Delta Arguments
Source: https://motion.dev/docs/react-use-animation-frame
Demonstrates importing and using the useAnimationFrame hook within a React component. The callback receives both total elapsed time and the time delta since the last frame.
```javascript
import { useAnimationFrame } from "motion/react"
function Component() {
const ref = useRef(null)
useAnimationFrame((time, delta) => {
ref.current.style.transform = `rotateY(${time}deg)`
})
return
}
```
--------------------------------
### Using LazyMotion for Reduced Bundle Size
Source: https://motion.dev/docs/react-upgrade-guide
Utilize the LazyMotion component with features like domAnimation to reduce bundle size by loading motion functionality on demand. This replaces the older MotionConfig features prop.
```jsx
import { LazyMotion, domAnimation, m } from "framer-motion"
export const MyComponent = ({ isVisible }) => (
)
```
--------------------------------
### Re-enabling Opacity with Custom Values
Source: https://motion.dev/docs/react-animate-view
To re-enable the 'opacity' animation alongside custom values like 'clipPath' for the 'enter' prop, include 'opacity: 1' in the animation object.
```jsx
```
--------------------------------
### Scoped Layout Animations with AnimateSharedLayout (Deprecated)
Source: https://motion.dev/docs/react-upgrade-guide
Illustrates the previous behavior where shared layout animations were scoped to individual AnimateSharedLayout components, which could lead to performance issues due to layout thrashing.
```jsx
/**
* These items share the same layoutId but won't animate
* between each other because they're children of different
* AnimateSharedLayout components.
*/
<>
{isVisible ? : null}
{isVisible ? : null}
>
```
--------------------------------
### Track Another Motion Value with useSpring
Source: https://motion.dev/docs/react-use-spring
Use useSpring to make a motion value automatically animate towards the latest value of another motion value.
```javascript
const x = useMotionValue(0)
const y = useSpring(x)
```
--------------------------------
### Dynamic Reduced Motion Setting
Source: https://motion.dev/docs/react-accessibility
Allow users to override the Reduced Motion setting for your site by dynamically setting the `reducedMotion` prop in `MotionConfig` based on user preferences.
```jsx
```
```
--------------------------------
### Typewriter with Immediate Backspace
Source: https://motion.dev/docs/react-typewriter
Set the backspace behavior to remove all mismatched content immediately by using the 'backspace' prop set to 'all'.
```jsx
{text}
```
--------------------------------
### Import Carousel Component
Source: https://motion.dev/docs/react-carousel
Import the Carousel component from the 'motion-plus/react' package.
```javascript
import { Carousel } from "motion-plus/react"
```
--------------------------------
### Basic LazyMotion Usage
Source: https://motion.dev/docs/react-lazy-motion
Use LazyMotion with domAnimation for basic lazy loading of motion components. This reduces the initial bundle size compared to the default motion component.
```jsx
import { LazyMotion, domAnimation } from "motion/react"
import * as m from "motion/react-m"
export const MyComponent = ({ isVisible }) => (
)
```
--------------------------------
### Basic Button Animation with Hover and Tap Effects
Source: https://motion.dev/docs/react-tailwind
Use this snippet for interactive buttons where Tailwind styles the static appearance and Motion handles hover and tap animations.
```jsx
import { motion } from "motion/react";
function Button() {
return (
Click Me!
);
}
```
--------------------------------
### useMotionValue Hook
Source: https://motion.dev/docs/react-motion-value
Creates a motion value with an initial state. This value can be used to track state and velocity for animations.
```APIDOC
## `useMotionValue(initialState)`
### Description
Creates a motion value with an initial state. The `initialState` can be a number or a string.
### Usage
```javascript
import { useMotionValue } from "motion/react"
const x = useMotionValue(0)
```
```
--------------------------------
### Configure Drag Threshold
Source: https://motion.dev/docs/react-use-drag-controls
Set a custom distance threshold for drag gesture initialization using the distanceThreshold option.
```javascript
controls.start(event, { distanceThreshold: 10 })
```
--------------------------------
### Adding Transition Types with addTransitionType
Source: https://motion.dev/docs/react-animate-view
Illustrates how to use React's addTransitionType to set contextual information, like navigation direction, for the current transition.
```jsx
startTransition(() => {
addTransitionType("next")
setItem(2)
})
```