framer-motion
- Version 11.15.0
- Published
- 3.02 MB
- 3 dependencies
- MIT license
Install
npm i framer-motion
yarn add framer-motion
pnpm add framer-motion
Overview
A simple and powerful JavaScript animation library
Index
Variables
- animate
- AnimatePresence
- AnimateSharedLayout
- animations
- backIn
- backInOut
- cancelSync
- circIn
- circInOut
- circOut
- color
- complex
- DeprecatedLayoutGroupContext
- domAnimation
- domMax
- domMin
- frame
- frameData
- frameSteps
- isBrowser
- LayoutGroup
- LayoutGroupContext
- m
- mirrorEasing
- motion
- MotionConfigContext
- MotionContext
- MotionGlobalConfig
- optimizedAppearDataAttribute
- PresenceContext
- px
- reverseEasing
- svgElements
- SwitchLayoutGroupContext
- sync
- time
- useAnimation
- useIsomorphicLayoutEffect
- visualElementStore
Functions
- addPointerEvent()
- addPointerInfo()
- addScaleCorrector()
- animateMini()
- animateValue()
- animateVisualElement()
- animationControls()
- anticipate()
- backOut()
- buildTransform()
- calcLength()
- cancelFrame()
- clamp()
- createBox()
- createRendererMotionComponent()
- createScopedAnimate()
- createTransformer()
- cubicBezier()
- delay()
- disableInstantTransitions()
- distance()
- distance2D()
- easeIn()
- easeInOut()
- easeOut()
- filterProps()
- findSpring()
- getAnimatableNone()
- inertia()
- interpolate()
- inView()
- isMotionComponent()
- isMotionValue()
- isValidMotionProp()
- keyframes()
- LazyMotion()
- makeUseVisualState()
- MeasureLayout()
- mix()
- MotionConfig()
- motionValue()
- parseComplexValue()
- pipe()
- progress()
- ReorderGroup()
- ReorderGroupComponent()
- ReorderItem()
- ReorderItemComponent()
- resolveMotionValue()
- scroll()
- scrollInfo()
- spring()
- stagger()
- startOptimizedAppearAnimation()
- steps()
- test()
- transform()
- unwrapMotionComponent()
- useAnimate()
- useAnimateMini()
- useAnimationControls()
- useAnimationFrame()
- useCycle()
- useDeprecatedAnimatedState()
- useDeprecatedInvertedScale()
- useDomEvent()
- useDragControls()
- useElementScroll()
- useForceUpdate()
- useInstantLayoutTransition()
- useInstantTransition()
- useInView()
- useIsPresent()
- useMotionTemplate()
- useMotionValue()
- useMotionValueEvent()
- usePresence()
- useReducedMotion()
- useReducedMotionConfig()
- useResetProjection()
- useScroll()
- useSpring()
- useTime()
- useTransform()
- useUnmountEffect()
- useVelocity()
- useViewportScroll()
- useWillChange()
- wrap()
Classes
VisualElement
- addValue()
- addVariantChild()
- animationState
- blockInitialAnimation
- build()
- children
- current
- depth
- getBaseTarget()
- getBaseTargetFromProps()
- getClosestVariantNode()
- getDefaultTransition()
- getProps()
- getStaticValue()
- getTransformPagePoint()
- getValue()
- getVariant()
- handleChildMotionValue()
- hasValue()
- isControllingVariants
- isVariantNode
- KeyframeResolver
- latestValues
- manuallyAnimateOnMount
- measureInstanceViewportBox()
- measureViewportBox()
- mount()
- notify()
- notifyUpdate
- on()
- options
- parent
- presenceContext
- prevPresenceContext
- prevProps
- projection
- props
- readValue()
- readValueFromInstance()
- removeValue()
- removeValueFromRenderState()
- render
- renderInstance()
- renderState
- scheduleRender
- scrapeMotionValuesFromProps()
- setBaseTarget()
- setStaticValue()
- shouldReduceMotion
- sortInstanceNodePosition()
- sortNodePosition()
- triggerBuild()
- type
- unmount()
- update()
- updateFeatures()
- values
- variantChildren
Interfaces
IProjectionNode
- addEventListener()
- animationId
- animationValues
- applyTransform()
- blockUpdate()
- calcProjection()
- checkUpdateFailed()
- children
- clearMeasurements()
- clearSnapshot()
- currentAnimation
- depth
- didUpdate()
- finishAnimation()
- getClosestProjectingParent()
- getProjectionStyles()
- getStack()
- hasCheckedOptimisedAppear
- hasListeners()
- hasTreeAnimated
- hide()
- id
- instance
- isAnimationBlocked
- isLayoutDirty
- isLead()
- isPresent
- isProjecting()
- isProjectionDirty
- isSharedProjectionDirty
- isTransformDirty
- isTreeAnimating
- isTreeAnimationBlocked
- isUpdateBlocked()
- isUpdating
- isVisible
- latestValues
- layout
- measure()
- measurePageBox()
- mount
- needsReset
- nodes
- notifyListeners()
- options
- parent
- path
- preserveOpacity
- prevTransformTemplateValue
- projectionDelta
- projectionDeltaWithTransform
- promote()
- registerSharedNode()
- relativeParent
- relativeTarget
- relativeTargetOrigin
- relegate()
- resetSkewAndRotation()
- resetTransform()
- resetTree()
- resolvedRelativeTargetAt
- resolveTargetDelta()
- resumeFrom
- resumingFrom
- root
- scheduleCheckAfterUnmount()
- scheduleRender()
- scheduleUpdateProjection()
- scroll
- setAnimationOrigin()
- setOptions()
- setTargetDelta()
- sharedNodes
- shouldResetTransform
- show()
- snapshot
- startAnimation()
- startUpdate()
- target
- targetDelta
- targetWithTransforms
- treeScale
- unblockUpdate()
- unmount
- updateBlockedByResize
- updateLayout()
- updateManuallyBlocked
- updateScroll()
- updateSnapshot()
- willUpdate()
Type Aliases
- AnimationDefinition
- AnimationGeneratorType
- AnimationOptionsWithValueOverrides
- AnimationSequence
- AnimationType
- BezierDefinition
- CreateVisualElement
- Cycle
- CycleState
- DelayedFunction
- Direction
- DOMKeyframesDefinition
- DOMMotionComponents
- DOMSegment
- DOMSegmentWithTransition
- DragElastic
- DynamicOption
- Easing
- EasingDefinition
- EasingFunction
- EasingModifier
- FeatureDefinition
- FeatureDefinitions
- FeaturePackage
- FeaturePackages
- ForwardRefComponent
- GeneratorFactory
- HTMLMotionProps
- HydratedFeatureDefinition
- KeyframesTarget
- LazyFeatureBundle
- MixerFactory
- MotionStyle
- MotionTransform
- MotionValueSegment
- MotionValueSegmentWithTransition
- ObjectSegment
- ObjectSegmentWithTransition
- ObjectTarget
- PassiveEffect
- RenderComponent
- RepeatType
- ResolvedAnimationDefinition
- ResolvedAnimationDefinitions
- ResolvedKeyframesTarget
- ResolvedSingleTarget
- ResolvedValueTarget
- ResolveKeyframes
- ScrapeMotionValuesFromProps
- Segment
- SequenceLabel
- SequenceTime
- SingleTarget
- StyleKeyframesDefinition
- StyleTransitions
- Subscriber
- SVGAttributesAsMotionValues
- SVGKeyframesDefinition
- SVGPathKeyframesDefinition
- SVGPathTransitions
- SVGTransitions
- SwitchLayoutGroupContext
- Target
- TargetAndTransition
- TransformPoint
- Transition
- UnresolvedValueKeyframe
- ValueKeyframe
- ValueKeyframesDefinition
- ValueSequence
- ValueTarget
- ValueType
- VariableKeyframesDefinition
- VariableTransitions
- Variant
- VariantLabels
- Variants
Namespaces
Variables
variable animate
const animate: { ( sequence: AnimationSequence, options?: SequenceOptions ): AnimationPlaybackControls; ( value: string | MotionValue<string>, keyframes: string | GenericKeyframesTarget<string>, options?: ValueAnimationTransition<string> ): AnimationPlaybackControls; ( value: number | MotionValue<number>, keyframes: number | GenericKeyframesTarget<number>, options?: ValueAnimationTransition<number> ): AnimationPlaybackControls; <V>( value: V | MotionValue<V>, keyframes: V | V[], options?: ValueAnimationTransition<V> ): AnimationPlaybackControls; ( element: ElementOrSelector, keyframes: DOMKeyframesDefinition, options?: DynamicAnimationOptions ): AnimationPlaybackControls; <O extends {}>( object: O | O[], keyframes: ObjectTarget<O>, options?: DynamicAnimationOptions ): AnimationPlaybackControls;};
variable AnimatePresence
const AnimatePresence: React$1.FunctionComponent< React$1.PropsWithChildren<AnimatePresenceProps>>;
AnimatePresence
enables the animation of components that have been removed from the tree.When adding/removing more than a single child, every child **must** be given a unique
key
prop.Any
motion
components that have anexit
property defined will animate out when removed from the tree.import { motion, AnimatePresence } from 'framer-motion'export const Items = ({ items }) => (<AnimatePresence>{items.map(item => (<motion.divkey={item.id}initial={{ opacity: 0 }}animate={{ opacity: 1 }}exit={{ opacity: 0 }}/>))}</AnimatePresence>)You can sequence exit animations throughout a tree using variants.
If a child contains multiple
motion
components withexit
props, it will only unmount the child once allmotion
components have finished animating out. Likewise, any components usingusePresence
all need to callsafeToRemove
.Modifiers
@public
variable AnimateSharedLayout
const AnimateSharedLayout: React$1.FunctionComponent< React$1.PropsWithChildren<unknown>>;
variable animations
const animations: FeaturePackages;
variable backIn
const backIn: EasingFunction;
variable backInOut
const backInOut: EasingFunction;
variable cancelSync
const cancelSync: Record<string, (process: Process) => void>;
Deprecated
Use cancelFrame(callback) instead.
variable circIn
const circIn: EasingFunction;
variable circInOut
const circInOut: EasingFunction;
variable circOut
const circOut: EasingFunction;
variable color
const color: { test: (v: any) => boolean; parse: (v: any) => RGBA | HSLA; transform: (v: HSLA | RGBA | string) => string;};
variable complex
const complex: { test: typeof test; parse: typeof parseComplexValue; createTransformer: typeof createTransformer; getAnimatableNone: typeof getAnimatableNone;};
variable DeprecatedLayoutGroupContext
const DeprecatedLayoutGroupContext: React$1.Context<string>;
Note: Still used by components generated by old versions of Framer
Deprecated
variable domAnimation
const domAnimation: FeatureBundle;
Modifiers
@public
variable domMax
const domMax: FeatureBundle;
Modifiers
@public
variable domMin
const domMin: FeatureBundle;
Modifiers
@public
variable frame
const frame: Batcher;
variable frameData
const frameData: FrameData;
variable frameSteps
const frameSteps: Steps;
variable isBrowser
const isBrowser: boolean;
variable LayoutGroup
const LayoutGroup: React$1.FunctionComponent<React$1.PropsWithChildren<Props$2>>;
variable LayoutGroupContext
const LayoutGroupContext: React$1.Context<LayoutGroupContextProps>;
variable m
const m: (<Props, TagName extends string = 'div'>( Component: any, { forwardMotionProps }?: { forwardMotionProps: boolean }) => TagName extends | 'symbol' | 'image' | 'animate' | 'clipPath' | 'filter' | 'marker' | 'mask' | 'path' | keyof HTMLElements | 'circle' | 'defs' | 'desc' | 'ellipse' | 'g' | 'line' | 'metadata' | 'pattern' | 'polygon' | 'polyline' | 'rect' | 'stop' | 'svg' | 'switch' | 'text' | 'tspan' | 'use' | 'view' | 'feBlend' | 'feColorMatrix' | 'feComponentTransfer' | 'feComposite' | 'feConvolveMatrix' | 'feDiffuseLighting' | 'feDisplacementMap' | 'feDistantLight' | 'feDropShadow' | 'feFlood' | 'feFuncA' | 'feFuncB' | 'feFuncG' | 'feFuncR' | 'feGaussianBlur' | 'feImage' | 'feMerge' | 'feMergeNode' | 'feMorphology' | 'feOffset' | 'fePointLight' | 'feSpecularLighting' | 'feSpotLight' | 'feTile' | 'feTurbulence' | 'foreignObject' | 'linearGradient' | 'radialGradient' | 'textPath' ? DOMMotionComponents[TagName] : React$1.ComponentType< MotionComponentProps<React$1.PropsWithChildren<Props>> >) & HTMLMotionComponents & SVGMotionComponents & { create: <Props, TagName extends string = 'div'>( Component: any, { forwardMotionProps }?: { forwardMotionProps: boolean } ) => TagName extends | 'symbol' | 'image' | 'animate' | 'clipPath' | 'filter' | 'marker' | 'mask' | 'path' | keyof HTMLElements | 'circle' | 'defs' | 'desc' | 'ellipse' | 'g' | 'line' | 'metadata' | 'pattern' | 'polygon' | 'polyline' | 'rect' | 'stop' | 'svg' | 'switch' | 'text' | 'tspan' | 'use' | 'view' | 'feBlend' | 'feColorMatrix' | 'feComponentTransfer' | 'feComposite' | 'feConvolveMatrix' | 'feDiffuseLighting' | 'feDisplacementMap' | 'feDistantLight' | 'feDropShadow' | 'feFlood' | 'feFuncA' | 'feFuncB' | 'feFuncG' | 'feFuncR' | 'feGaussianBlur' | 'feImage' | 'feMerge' | 'feMergeNode' | 'feMorphology' | 'feOffset' | 'fePointLight' | 'feSpecularLighting' | 'feSpotLight' | 'feTile' | 'feTurbulence' | 'foreignObject' | 'linearGradient' | 'radialGradient' | 'textPath' ? DOMMotionComponents[TagName] : React$1.ComponentType< MotionComponentProps<React$1.PropsWithChildren<Props>> >; };
variable mirrorEasing
const mirrorEasing: EasingModifier;
variable motion
const motion: (<Props, TagName extends string = 'div'>( Component: any, { forwardMotionProps }?: { forwardMotionProps: boolean }) => TagName extends | 'symbol' | 'image' | 'animate' | 'clipPath' | 'filter' | 'marker' | 'mask' | 'path' | keyof HTMLElements | 'circle' | 'defs' | 'desc' | 'ellipse' | 'g' | 'line' | 'metadata' | 'pattern' | 'polygon' | 'polyline' | 'rect' | 'stop' | 'svg' | 'switch' | 'text' | 'tspan' | 'use' | 'view' | 'feBlend' | 'feColorMatrix' | 'feComponentTransfer' | 'feComposite' | 'feConvolveMatrix' | 'feDiffuseLighting' | 'feDisplacementMap' | 'feDistantLight' | 'feDropShadow' | 'feFlood' | 'feFuncA' | 'feFuncB' | 'feFuncG' | 'feFuncR' | 'feGaussianBlur' | 'feImage' | 'feMerge' | 'feMergeNode' | 'feMorphology' | 'feOffset' | 'fePointLight' | 'feSpecularLighting' | 'feSpotLight' | 'feTile' | 'feTurbulence' | 'foreignObject' | 'linearGradient' | 'radialGradient' | 'textPath' ? DOMMotionComponents[TagName] : React$1.ComponentType< MotionComponentProps<React$1.PropsWithChildren<Props>> >) & HTMLMotionComponents & SVGMotionComponents & { create: <Props, TagName extends string = 'div'>( Component: any, { forwardMotionProps }?: { forwardMotionProps: boolean } ) => TagName extends | 'symbol' | 'image' | 'animate' | 'clipPath' | 'filter' | 'marker' | 'mask' | 'path' | keyof HTMLElements | 'circle' | 'defs' | 'desc' | 'ellipse' | 'g' | 'line' | 'metadata' | 'pattern' | 'polygon' | 'polyline' | 'rect' | 'stop' | 'svg' | 'switch' | 'text' | 'tspan' | 'use' | 'view' | 'feBlend' | 'feColorMatrix' | 'feComponentTransfer' | 'feComposite' | 'feConvolveMatrix' | 'feDiffuseLighting' | 'feDisplacementMap' | 'feDistantLight' | 'feDropShadow' | 'feFlood' | 'feFuncA' | 'feFuncB' | 'feFuncG' | 'feFuncR' | 'feGaussianBlur' | 'feImage' | 'feMerge' | 'feMergeNode' | 'feMorphology' | 'feOffset' | 'fePointLight' | 'feSpecularLighting' | 'feSpotLight' | 'feTile' | 'feTurbulence' | 'foreignObject' | 'linearGradient' | 'radialGradient' | 'textPath' ? DOMMotionComponents[TagName] : React$1.ComponentType< MotionComponentProps<React$1.PropsWithChildren<Props>> >; };
variable MotionConfigContext
const MotionConfigContext: React$1.Context<MotionConfigContext>;
Modifiers
@public
variable MotionContext
const MotionContext: React$1.Context<MotionContextProps<unknown>>;
variable MotionGlobalConfig
const MotionGlobalConfig: { skipAnimations: boolean; useManualTiming: boolean };
variable optimizedAppearDataAttribute
const optimizedAppearDataAttribute: string;
variable PresenceContext
const PresenceContext: React$1.Context<PresenceContextProps>;
Modifiers
@public
variable px
const px: { test: (v: string | number) => boolean; parse: typeof parseFloat; transform: (v: number | string) => string;};
variable reverseEasing
const reverseEasing: EasingModifier;
variable svgElements
const svgElements: readonly [ 'animate', 'circle', 'defs', 'desc', 'ellipse', 'g', 'image', 'line', 'filter', 'marker', 'mask', 'metadata', 'path', 'pattern', 'polygon', 'polyline', 'rect', 'stop', 'svg', 'switch', 'symbol', 'text', 'tspan', 'use', 'view', 'clipPath', 'feBlend', 'feColorMatrix', 'feComponentTransfer', 'feComposite', 'feConvolveMatrix', 'feDiffuseLighting', 'feDisplacementMap', 'feDistantLight', 'feDropShadow', 'feFlood', 'feFuncA', 'feFuncB', 'feFuncG', 'feFuncR', 'feGaussianBlur', 'feImage', 'feMerge', 'feMergeNode', 'feMorphology', 'feOffset', 'fePointLight', 'feSpecularLighting', 'feSpotLight', 'feTile', 'feTurbulence', 'foreignObject', 'linearGradient', 'radialGradient', 'textPath'];
variable SwitchLayoutGroupContext
const SwitchLayoutGroupContext: React$1.Context<SwitchLayoutGroupContext>;
Internal, exported only for usage in Framer
variable sync
const sync: Batcher;
Deprecated
Import as
frame
instead.
variable time
const time: { now: () => number; set: (newTime: number) => void };
An eventloop-synchronous alternative to performance.now().
Ensures that time measurements remain consistent within a synchronous context. Usually calling performance.now() twice within the same synchronous context will return different values which isn't useful for animations when we're usually trying to sync animations to the same frame.
variable useAnimation
const useAnimation: () => AnimationControls;
variable useIsomorphicLayoutEffect
const useIsomorphicLayoutEffect: any;
variable visualElementStore
const visualElementStore: WeakMap<any, VisualElement<unknown, unknown, {}>>;
Functions
function addPointerEvent
addPointerEvent: ( target: EventTarget, eventName: string, handler: EventListenerWithPointInfo, options?: AddEventListenerOptions) => () => void;
function addPointerInfo
addPointerInfo: (handler: EventListenerWithPointInfo) => EventListener;
function addScaleCorrector
addScaleCorrector: (correctors: ScaleCorrectorMap) => void;
function animateMini
animateMini: ( elementOrSelector: ElementOrSelector, keyframes: DOMKeyframesDefinition, options?: DynamicAnimationOptions) => AnimationPlaybackControls;
function animateValue
animateValue: ( options: ValueAnimationOptionsWithRenderContext<any>) => MainThreadAnimation<any>;
function animateVisualElement
animateVisualElement: ( visualElement: VisualElement, definition: AnimationDefinition, options?: VisualElementAnimationOptions) => Promise<void>;
function animationControls
animationControls: () => AnimationControls;
Modifiers
@public
function anticipate
anticipate: (p: number) => number;
function backOut
backOut: (t: number) => number;
function buildTransform
buildTransform: ( latestValues: ResolvedValues, transform: HTMLRenderState['transform'], transformTemplate?: MotionProps['transformTemplate']) => string;
Build a CSS transform style from individual x/y/scale etc properties.
This outputs with a default order of transforms/scales/rotations, this can be customised by providing a transformTemplate function.
function calcLength
calcLength: (axis: Axis) => number;
function cancelFrame
cancelFrame: (process: Process) => void;
function clamp
clamp: (min: number, max: number, v: number) => number;
function createBox
createBox: () => Box;
function createRendererMotionComponent
createRendererMotionComponent: <Props extends {}, Instance, RenderState>({ preloadedFeatures, createVisualElement, useRender, useVisualState, Component,}: MotionComponentConfig< Instance, RenderState>) => React$1.ForwardRefExoticComponent<React$1.RefAttributes<unknown>>;
Create a
motion
component.This function accepts a Component argument, which can be either a string (ie "div" for
motion.div
), or an actual React component.Alongside this is a config option which provides a way of rendering the provided component "offline", or outside the React render cycle.
function createScopedAnimate
createScopedAnimate: (scope?: AnimationScope) => { ( sequence: AnimationSequence, options?: SequenceOptions ): AnimationPlaybackControls; ( value: string | MotionValue<string>, keyframes: string | GenericKeyframesTarget<string>, options?: ValueAnimationTransition<string> ): AnimationPlaybackControls; ( value: number | MotionValue<number>, keyframes: number | GenericKeyframesTarget<number>, options?: ValueAnimationTransition<number> ): AnimationPlaybackControls; <V>( value: V | MotionValue<V>, keyframes: V | V[], options?: ValueAnimationTransition<V> ): AnimationPlaybackControls; ( element: ElementOrSelector, keyframes: DOMKeyframesDefinition, options?: DynamicAnimationOptions ): AnimationPlaybackControls; <O extends {}>( object: O | O[], keyframes: ObjectTarget<O>, options?: DynamicAnimationOptions ): AnimationPlaybackControls;};
Creates an animation function that is optionally scoped to a specific element.
function createTransformer
createTransformer: ( source: string | number) => (v: Array<CSSVariableToken | Color | number | string>) => string;
function cubicBezier
cubicBezier: ( mX1: number, mY1: number, mX2: number, mY2: number) => (t: number) => number;
function delay
delay: (callback: DelayedFunction, timeout: number) => () => void;
Timeout defined in ms
function disableInstantTransitions
disableInstantTransitions: () => void;
function distance
distance: (a: number, b: number) => number;
function distance2D
distance2D: (a: Point, b: Point) => number;
function easeIn
easeIn: (t: number) => number;
function easeInOut
easeInOut: (t: number) => number;
function easeOut
easeOut: (t: number) => number;
function filterProps
filterProps: ( props: MotionProps, isDom: boolean, forwardMotionProps: boolean) => MotionProps;
function findSpring
findSpring: ({ duration, bounce, velocity, mass }: SpringOptions) => { stiffness: number; damping: number; duration: number;};
function getAnimatableNone
getAnimatableNone: (v: string | number) => string;
function inertia
inertia: ({ keyframes, velocity, power, timeConstant, bounceDamping, bounceStiffness, modifyTarget, min, max, restDelta, restSpeed,}: ValueAnimationOptions<number>) => KeyframeGenerator<number>;
function interpolate
interpolate: <T>( input: number[], output: T[], { clamp: isClamp, ease, mixer }?: InterpolateOptions<T>) => (v: number) => T;
Create a function that maps from a numerical input array to a generic output array.
Accepts: - Numbers - Colors (hex, hsl, hsla, rgb, rgba) - Complex (combinations of one or more numbers or strings)
const mixColor = interpolate([0, 1], ['#fff', '#000'])mixColor(0.5) // 'rgba(128, 128, 128, 1)'TODO Revist this approach once we've moved to data models for values, probably not needed to pregenerate mixer functions.
Modifiers
@public
function inView
inView: ( elementOrSelector: ElementOrSelector, onStart: (entry: IntersectionObserverEntry) => void | ViewChangeHandler, { root, margin: rootMargin, amount }?: InViewOptions) => VoidFunction;
function isMotionComponent
isMotionComponent: (component: React.ComponentType | string) => boolean;
Checks if a component is a
motion
component.
function isMotionValue
isMotionValue: (value: any) => value is MotionValue<any>;
function isValidMotionProp
isValidMotionProp: (key: string) => boolean;
Check whether a prop name is a valid
MotionProp
key.Parameter key
Name of the property to check
Returns
true
is key is a validMotionProp
.Modifiers
@public
function keyframes
keyframes: <T extends string | number>({ duration, keyframes: keyframeValues, times, ease,}: ValueAnimationOptions<T>) => KeyframeGenerator<T>;
function LazyMotion
LazyMotion: ({ children, features, strict,}: LazyProps) => react_jsx_runtime.JSX.Element;
Used in conjunction with the
m
component to reduce bundle size.m
is a version of themotion
component that only loads functionality critical for the initial render.LazyMotion
can then be used to either synchronously or asynchronously load animation and gesture support.// Synchronous loadingimport { LazyMotion, m, domAnimation } from "framer-motion"function App() {return (<LazyMotion features={domAnimation}><m.div animate={{ scale: 2 }} /></LazyMotion>)}// Asynchronous loadingimport { LazyMotion, m } from "framer-motion"function App() {return (<LazyMotion features={() => import('./path/to/domAnimation')}><m.div animate={{ scale: 2 }} /></LazyMotion>)}Modifiers
@public
function makeUseVisualState
makeUseVisualState: <I, RS>( config: UseVisualStateConfig<I, RS>) => UseVisualState<I, RS>;
function MeasureLayout
MeasureLayout: ( props: MotionProps & { visualElement: VisualElement }) => react_jsx_runtime.JSX.Element;
function mix
mix: { <T>(from: T, to: T): Mixer<T>; (from: number, to: number, p: number): number;};
function MotionConfig
MotionConfig: ({ children, isValidProp, ...config}: MotionConfigProps) => react_jsx_runtime.JSX.Element;
MotionConfig
is used to set configuration options for all childrenmotion
components.import { motion, MotionConfig } from "framer-motion"export function App() {return (<MotionConfig transition={{ type: "spring" }}><motion.div animate={{ x: 100 }} /></MotionConfig>)}Modifiers
@public
function motionValue
motionValue: <V>(init: V, options?: MotionValueOptions) => MotionValue<V>;
function parseComplexValue
parseComplexValue: (v: string | number) => ComplexValues;
function pipe
pipe: (...transformers: Function[]) => Function;
function progress
progress: (from: number, to: number, value: number) => number;
function ReorderGroup
ReorderGroup: <V>(props: any) => react_jsx_runtime.JSX.Element;
function ReorderGroupComponent
ReorderGroupComponent: <V>( { children, as, axis, onReorder, values, ...props }: ReorderGroupProps<V>, externalRef?: React$1.ForwardedRef<any>) => react_jsx_runtime.JSX.Element;
function ReorderItem
ReorderItem: <V>(props: any) => react_jsx_runtime.JSX.Element;
function ReorderItemComponent
ReorderItemComponent: <V>( { children, style, value, as, onDrag, layout, ...props }: ReorderItemProps<V>, externalRef?: React$1.ForwardedRef<any>) => react_jsx_runtime.JSX.Element;
function resolveMotionValue
resolveMotionValue: ( value?: string | number | CustomValueType | MotionValue) => string | number;
If the provided value is a MotionValue, this returns the actual value, otherwise just the value itself
TODO: Remove and move to library
function scroll
scroll: ( onScroll: OnScroll | AnimationPlaybackControls, { axis, ...options }?: ScrollOptions) => VoidFunction;
function scrollInfo
scrollInfo: ( onScroll: OnScrollInfo, { container, ...options }?: ScrollInfoOptions) => () => void;
function spring
spring: ( optionsOrVisualDuration?: ValueAnimationOptions<number> | number, bounce?: number) => KeyframeGenerator<number>;
function stagger
stagger: ( duration?: number, { startDelay, from, ease }?: StaggerOptions) => DynamicOption<number>;
function startOptimizedAppearAnimation
startOptimizedAppearAnimation: ( element: HTMLElement, name: string, keyframes: string[] | number[], options: NativeAnimationOptions, onReady?: (animation: Animation) => void) => void;
function steps
steps: (numSteps: number, direction?: Direction) => EasingFunction;
function test
test: (v: any) => boolean;
function transform
transform: { <T>( inputValue: number, inputRange: number[], outputRange: T[], options?: TransformOptions<T> ): T; <T>(inputRange: number[], outputRange: T[], options?: TransformOptions<T>): ( inputValue: number ) => T;};
Transforms numbers into other values by mapping them from an input range to an output range. Returns the type of the input provided.
Parameter inputValue
A number to transform between the input and output ranges.
Parameter inputRange
A linear series of numbers (either all increasing or decreasing).
Parameter outputRange
A series of numbers, colors, strings, or arrays/objects of those. Must be the same length as
inputRange
.Parameter options
Clamp: Clamp values to within the given range. Defaults to
true
.Remarks
Given an input range of
[0, 200]
and an output range of[0, 1]
, this function will return a value between0
and1
. The input range must be a linear series of numbers. The output range can be any supported value type, such as numbers, colors, shadows, arrays, objects and more. Every value in the output range must be of the same type and in the same format.import * as React from "react"import { transform } from "framer-motion"export function MyComponent() {const inputRange = [0, 200]const outputRange = [0, 1]const output = transform(100, inputRange, outputRange)// Returns 0.5return <div>{output}</div>}Modifiers
@public
Transforms numbers into other values by mapping them from an input range to an output range.
Given an input range of
[0, 200]
and an output range of[0, 1]
, this function will return a value between0
and1
. The input range must be a linear series of numbers. The output range can be any supported value type, such as numbers, colors, shadows, arrays, objects and more. Every value in the output range must be of the same type and in the same format.import * as React from "react"import { Frame, transform } from "framer"export function MyComponent() {const inputRange = [-200, -100, 100, 200]const outputRange = [0, 1, 1, 0]const convertRange = transform(inputRange, outputRange)const output = convertRange(-150)// Returns 0.5return <div>{output}</div>}Parameter inputRange
A linear series of numbers (either all increasing or decreasing).
Parameter outputRange
A series of numbers, colors or strings. Must be the same length as
inputRange
.Parameter options
Clamp: clamp values to within the given range. Defaults to
true
.Modifiers
@public
function unwrapMotionComponent
unwrapMotionComponent: ( component: React.ComponentType | string) => React.ComponentType | string | undefined;
Unwraps a
motion
component and returns either a string formotion.div
or the React component formotion(Component)
.If the component is not a
motion
component it returns undefined.
function useAnimate
useAnimate: <T extends Element = any>() => [ AnimationScope<T>, { ( sequence: AnimationSequence, options?: SequenceOptions | undefined ): AnimationPlaybackControls; ( value: string | MotionValue<string>, keyframes: string | GenericKeyframesTarget<string>, options?: ValueAnimationTransition<string> | undefined ): AnimationPlaybackControls; ( value: number | MotionValue<number>, keyframes: number | GenericKeyframesTarget<number>, options?: ValueAnimationTransition<number> | undefined ): AnimationPlaybackControls; <V>( value: V | MotionValue<V>, keyframes: V | V[], options?: ValueAnimationTransition<V> ): AnimationPlaybackControls; ( element: motion_dom.ElementOrSelector, keyframes: DOMKeyframesDefinition, options?: DynamicAnimationOptions | undefined ): AnimationPlaybackControls; <O extends {}>( object: O | O[], keyframes: ObjectTarget<O>, options?: DynamicAnimationOptions | undefined ): AnimationPlaybackControls; }];
function useAnimateMini
useAnimateMini: <T extends Element = any>() => [ AnimationScope<T>, ( elementOrSelector: motion_dom.ElementOrSelector, keyframes: DOMKeyframesDefinition, options?: DynamicAnimationOptions | undefined ) => AnimationPlaybackControls];
function useAnimationControls
useAnimationControls: () => AnimationControls;
Creates
AnimationControls
, which can be used to manually start, stop and sequence animations on one or more components.The returned
AnimationControls
should be passed to theanimate
property of the components you want to animate.These components can then be animated with the
start
method.import * as React from 'react'import { motion, useAnimation } from 'framer-motion'export function MyComponent(props) {const controls = useAnimation()controls.start({x: 100,transition: { duration: 0.5 },})return <motion.div animate={controls} />}Returns
Animation controller with
start
andstop
methodsModifiers
@public
function useAnimationFrame
useAnimationFrame: (callback: FrameCallback) => void;
function useCycle
useCycle: <T>(...items: T[]) => CycleState<T>;
Cycles through a series of visual properties. Can be used to toggle between or cycle through animations. It works similar to
useState
in React. It is provided an initial array of possible states, and returns an array of two arguments.An index value can be passed to the returned
cycle
function to cycle to a specific index.import * as React from "react"import { motion, useCycle } from "framer-motion"export const MyComponent = () => {const [x, cycleX] = useCycle(0, 50, 100)return (<motion.divanimate={{ x: x }}onTap={() => cycleX()}/>)}Parameter items
items to cycle through
Returns
[currentState, cycleState]
Modifiers
@public
function useDeprecatedAnimatedState
useDeprecatedAnimatedState: (initialState: any) => any[];
This is not an officially supported API and may be removed on any version.
function useDeprecatedInvertedScale
useDeprecatedInvertedScale: ( scale?: Partial<ScaleMotionValues>) => ScaleMotionValues;
Returns a
MotionValue
each forscaleX
andscaleY
that update with the inverse of their respective parent scales.This is useful for undoing the distortion of content when scaling a parent component.
By default,
useInvertedScale
will automatically fetchscaleX
andscaleY
from the nearest parent. By passing otherMotionValue
s in asuseInvertedScale({ scaleX, scaleY })
, it will invert the output of those instead.const MyComponent = () => {const { scaleX, scaleY } = useInvertedScale()return <motion.div style={{ scaleX, scaleY }} />}Deprecated
function useDomEvent
useDomEvent: ( ref: RefObject$1<EventTarget>, eventName: string, handler?: EventListener | undefined, options?: AddEventListenerOptions) => void;
Attaches an event listener directly to the provided DOM element.
Bypassing React's event system can be desirable, for instance when attaching non-passive event handlers.
const ref = useRef(null)useDomEvent(ref, 'wheel', onWheel, { passive: false })return <div ref={ref} />Parameter ref
React.RefObject that's been provided to the element you want to bind the listener to.
Parameter eventName
Name of the event you want listen for.
Parameter handler
Function to fire when receiving the event.
Parameter options
Options to pass to
Event.addEventListener
.Modifiers
@public
function useDragControls
useDragControls: () => DragControls;
Usually, dragging is initiated by pressing down on a
motion
component with adrag
prop and moving it. For some use-cases, for instance clicking at an arbitrary point on a video scrubber, we might want to initiate that dragging from a different component than the draggable one.By creating a
dragControls
using theuseDragControls
hook, we can pass this into the draggable component'sdragControls
prop. It exposes astart
method that can start dragging from pointer events on other components.const dragControls = useDragControls()function startDrag(event) {dragControls.start(event, { snapToCursor: true })}return (<><div onPointerDown={startDrag} /><motion.div drag="x" dragControls={dragControls} /></>)Modifiers
@public
function useElementScroll
useElementScroll: (ref: RefObject$1<HTMLElement>) => { scrollX: MotionValue<number>; scrollY: MotionValue<number>; scrollXProgress: MotionValue<number>; scrollYProgress: MotionValue<number>;};
Deprecated
useElementScroll is deprecated. Convert to useScroll({ container: ref })
function useForceUpdate
useForceUpdate: () => [VoidFunction, number];
function useInstantLayoutTransition
useInstantLayoutTransition: () => (cb?: (() => void) | undefined) => void;
function useInstantTransition
useInstantTransition: () => (callback: () => void) => void;
function useInView
useInView: ( ref: RefObject$1<Element>, { root, margin, amount, once }?: UseInViewOptions) => boolean;
function useIsPresent
useIsPresent: () => boolean;
Similar to
usePresence
, exceptuseIsPresent
simply returns whether or not the component is present. There is nosafeToRemove
function.import { useIsPresent } from "framer-motion"export const Component = () => {const isPresent = useIsPresent()useEffect(() => {!isPresent && console.log("I've been removed!")}, [isPresent])return <div />}Modifiers
@public
function useMotionTemplate
useMotionTemplate: ( fragments: TemplateStringsArray, ...values: Array<MotionValue | number | string>) => MotionValue<string>;
Combine multiple motion values into a new one using a string template literal.
import {motion,useSpring,useMotionValue,useMotionTemplate} from "framer-motion"function Component() {const shadowX = useSpring(0)const shadowY = useMotionValue(0)const shadow = useMotionTemplate`drop-shadow(${shadowX}px ${shadowY}px 20px rgba(0,0,0,0.3))`return <motion.div style={{ filter: shadow }} />}Modifiers
@public
function useMotionValue
useMotionValue: <T>(initial: T) => MotionValue<T>;
Creates a
MotionValue
to track the state and velocity of a value.Usually, these are created automatically. For advanced use-cases, like use with
useTransform
, you can createMotionValue
s externally and pass them into the animated component via thestyle
prop.export const MyComponent = () => {const scale = useMotionValue(1)return <motion.div style={{ scale }} />}Parameter initial
The initial state.
Modifiers
@public
function useMotionValueEvent
useMotionValueEvent: <V, EventName extends keyof MotionValueEventCallbacks<V>>( value: MotionValue<V>, event: EventName, callback: MotionValueEventCallbacks<V>[EventName]) => void;
function usePresence
usePresence: () => AlwaysPresent | Present | NotPresent;
When a component is the child of
AnimatePresence
, it can useusePresence
to access information about whether it's still present in the React tree.import { usePresence } from "framer-motion"export const Component = () => {const [isPresent, safeToRemove] = usePresence()useEffect(() => {!isPresent && setTimeout(safeToRemove, 1000)}, [isPresent])return <div />}If
isPresent
isfalse
, it means that a component has been removed the tree, butAnimatePresence
won't really remove it untilsafeToRemove
has been called.Modifiers
@public
function useReducedMotion
useReducedMotion: () => boolean | null;
A hook that returns
true
if we should be using reduced motion based on the current device's Reduced Motion setting.This can be used to implement changes to your UI based on Reduced Motion. For instance, replacing motion-sickness inducing
x
/y
animations withopacity
, disabling the autoplay of background videos, or turning off parallax motion.It will actively respond to changes and re-render your components with the latest setting.
export function Sidebar({ isOpen }) {const shouldReduceMotion = useReducedMotion()const closedX = shouldReduceMotion ? 0 : "-100%"return (<motion.div animate={{opacity: isOpen ? 1 : 0,x: isOpen ? 0 : closedX}} />)}boolean
Modifiers
@public
function useReducedMotionConfig
useReducedMotionConfig: () => boolean | null;
function useResetProjection
useResetProjection: () => () => void;
function useScroll
useScroll: ({ container, target, layoutEffect, ...options}?: UseScrollOptions) => { scrollX: MotionValue<number>; scrollY: MotionValue<number>; scrollXProgress: MotionValue<number>; scrollYProgress: MotionValue<number>;};
function useSpring
useSpring: ( source: MotionValue<string> | MotionValue<number> | number, config?: SpringOptions) => MotionValue<number>;
Creates a
MotionValue
that, whenset
, will use a spring animation to animate to its new state.It can either work as a stand-alone
MotionValue
by initialising it with a value, or as a subscriber to anotherMotionValue
.Parameter inputValue
MotionValue
or number. If provided aMotionValue
, when the inputMotionValue
changes, the createdMotionValue
will spring towards that value.Parameter springConfig
Configuration options for the spring.
Returns
MotionValue
Remarks
const x = useSpring(0, { stiffness: 300 })const y = useSpring(x, { damping: 10 })Modifiers
@public
function useTime
useTime: () => MotionValue<number>;
function useTransform
useTransform: { <I, O>( value: MotionValue<number>, inputRange: InputRange, outputRange: O[], options?: TransformOptions<O> ): MotionValue<O>; <I, O>( input: MotionValue<I>, transformer: SingleTransformer<I, O> ): MotionValue<O>; <I, O>( input: | MotionValue<string>[] | MotionValue<number>[] | MotionValue<string | number>[], transformer: MultiTransformer<I, O> ): MotionValue<O>; <I, O>(transformer: () => O): MotionValue<O>;};
Create a
MotionValue
that transforms the output of anotherMotionValue
by mapping it from one range of values into another.Parameter inputValue
MotionValue
Parameter inputRange
A linear series of numbers (either all increasing or decreasing)
Parameter outputRange
A series of numbers, colors or strings. Must be the same length as
inputRange
.Parameter options
- clamp: boolean. Clamp values to within the given range. Defaults to
true
- ease: EasingFunction[]. Easing functions to use on the interpolations between each value in the input and output ranges. If provided as an array, the array must be one item shorter than the input and output ranges, as the easings apply to the transition between each.Returns
MotionValue
Remarks
Given an input range of
[-200, -100, 100, 200]
and an output range of[0, 1, 1, 0]
, the returnedMotionValue
will:- When provided a value between
-200
and-100
, will return a value between0
and1
. - When provided a value between-100
and100
, will return1
. - When provided a value between100
and200
, will return a value between1
and0
The input range must be a linear series of numbers. The output range can be any value type supported by Motion: numbers, colors, shadows, etc.
Every value in the output range must be of the same type and in the same format.
export const MyComponent = () => {const x = useMotionValue(0)const xRange = [-200, -100, 100, 200]const opacityRange = [0, 1, 1, 0]const opacity = useTransform(x, xRange, opacityRange)return (<motion.divanimate={{ x: 200 }}style={{ opacity, x }}/>)}Modifiers
@public
Create a
MotionValue
that transforms the output of anotherMotionValue
through a function. In this example,y
will always be doublex
.export const MyComponent = () => {const x = useMotionValue(10)const y = useTransform(x, value => value * 2)return <motion.div style={{ x, y }} />}Parameter input
A
MotionValue
that will pass its latest value throughtransform
to update the returnedMotionValue
.Parameter transform
A function that accepts the latest value from
input
and returns a new value.Returns
MotionValue
Modifiers
@public
Pass an array of
MotionValue
s and a function to combine them. In this example,z
will be thex
multiplied byy
.export const MyComponent = () => {const x = useMotionValue(0)const y = useMotionValue(0)const z = useTransform([x, y], ([latestX, latestY]) => latestX * latestY)return <motion.div style={{ x, y, z }} />}Parameter input
An array of
MotionValue
s that will pass their latest values throughtransform
to update the returnedMotionValue
.Parameter transform
A function that accepts the latest values from
input
and returns a new value.Returns
MotionValue
Modifiers
@public
function useUnmountEffect
useUnmountEffect: (callback: () => void) => void;
function useVelocity
useVelocity: (value: MotionValue<number>) => MotionValue<number>;
Creates a
MotionValue
that updates when the velocity of the providedMotionValue
changes.const x = useMotionValue(0)const xVelocity = useVelocity(x)const xAcceleration = useVelocity(xVelocity)Modifiers
@public
function useViewportScroll
useViewportScroll: () => { scrollX: MotionValue<number>; scrollY: MotionValue<number>; scrollXProgress: MotionValue<number>; scrollYProgress: MotionValue<number>;};
Deprecated
useViewportScroll is deprecated. Convert to useScroll()
function useWillChange
useWillChange: () => WillChange;
function wrap
wrap: (min: number, max: number, v: number) => number;
Classes
class AcceleratedAnimation
class AcceleratedAnimation<T extends string | number> extends BaseAnimation< T, ResolvedAcceleratedAnimation> {}
constructor
constructor(options: ValueAnimationOptionsWithRenderContext<T>);
property duration
readonly duration: number;
property options
protected options: ValueAnimationOptionsWithDefaults<T> & { name: string; motionValue: MotionValue<T>;};
property speed
speed: number;
property startTime
readonly startTime: number;
property state
readonly state: AnimationPlayState;
property time
time: number;
method attachTimeline
attachTimeline: (timeline: any) => (any: void) => void;
Replace the default DocumentTimeline with another AnimationTimeline. Currently used for scroll animations.
method cancel
cancel: () => void;
method complete
complete: () => void;
method initPlayback
protected initPlayback: ( keyframes: ResolvedKeyframes<T>, finalKeyframe: T) => | false | { animation: Animation; duration: number; times: number[] | undefined; type: AnimationGeneratorType | undefined; ease: Easing | Easing[] | undefined; keyframes: number[] | string[]; };
method pause
pause: () => void;
method play
play: () => void;
method stop
stop: () => void;
method supports
static supports: ( options: ValueAnimationOptionsWithRenderContext) => options is AcceleratedValueAnimationOptions<number>;
class DragControls
class DragControls {}
Can manually trigger a drag gesture on one or more
drag
-enabledmotion
components.const dragControls = useDragControls()function startDrag(event) {dragControls.start(event, { snapToCursor: true })}return (<><div onPointerDown={startDrag} /><motion.div drag="x" dragControls={dragControls} /></>)Modifiers
@public
method start
start: ( event: React$1.PointerEvent | PointerEvent, options?: DragControlOptions) => void;
Start a drag gesture on every
motion
component that has this set of drag controls passed into it via thedragControls
prop.dragControls.start(e, {snapToCursor: true})Parameter event
PointerEvent
Parameter options
Options
Modifiers
@public
class FlatTree
class FlatTree {}
class MotionValue
class MotionValue<V = any> {}
MotionValue
is used to track the state and velocity of motion values.Modifiers
@public
property animation
animation?: AnimationPlaybackControls;
A reference to the currently-controlling animation.
property hasAnimated
hasAnimated: boolean;
property owner
owner?: Owner;
If a MotionValue has an owner, it was created internally within Motion and therefore has no external listeners. It is therefore safe to animate via WAAPI.
property prevUpdatedAt
prevUpdatedAt: number;
The time
prevFrameValue
was updated.
property updateAndNotify
updateAndNotify: (v: V, render?: boolean) => void;
property updatedAt
updatedAt: number;
The last time the
MotionValue
was updated.
property version
version: string;
This will be replaced by the build step with the latest version number. When MotionValues are provided to motion components, warn if versions are mixed.
method clearListeners
clearListeners: () => void;
method destroy
destroy: () => void;
Destroy and clean up subscribers to this
MotionValue
.The
MotionValue
hooks likeuseMotionValue
anduseTransform
automatically handle the lifecycle of the returnedMotionValue
, so this method is only necessary if you've manually created aMotionValue
via themotionValue
function.Modifiers
@public
method get
get: () => NonNullable<V>;
Returns the latest state of
MotionValue
Returns
- The latest state of
MotionValue
Modifiers
@public
method getPrevious
getPrevious: () => V | undefined;
Modifiers
@public
method getVelocity
getVelocity: () => number;
Returns the latest velocity of
MotionValue
Returns
- The latest velocity of
MotionValue
. Returns0
if the state is non-numerical.Modifiers
@public
method isAnimating
isAnimating: () => boolean;
Returns
true
if this value is currently animating.Modifiers
@public
method jump
jump: (v: V, endAnimation?: boolean) => void;
Set the state of the
MotionValue
, stopping any active animations, effects, and resets velocity to0
.
method on
on: <EventName extends keyof MotionValueEventCallbacks<V>>( eventName: EventName, callback: MotionValueEventCallbacks<V>[EventName]) => VoidFunction;
method onChange
onChange: (subscription: Subscriber<V>) => () => void;
Adds a function that will be notified when the
MotionValue
is updated.It returns a function that, when called, will cancel the subscription.
When calling
onChange
inside a React component, it should be wrapped with theuseEffect
hook. As it returns an unsubscribe function, this should be returned from theuseEffect
function to ensure you don't add duplicate subscribers..export const MyComponent = () => {const x = useMotionValue(0)const y = useMotionValue(0)const opacity = useMotionValue(1)useEffect(() => {function updateOpacity() {const maxXY = Math.max(x.get(), y.get())const newOpacity = transform(maxXY, [0, 100], [1, 0])opacity.set(newOpacity)}const unsubscribeX = x.on("change", updateOpacity)const unsubscribeY = y.on("change", updateOpacity)return () => {unsubscribeX()unsubscribeY()}}, [])return <motion.div style={{ x }} />}Parameter subscriber
A function that receives the latest value.
Returns
A function that, when called, will cancel this subscription.
Deprecated
method set
set: (v: V, render?: boolean) => void;
Sets the state of the
MotionValue
.Parameter latest
Latest value to set.
Parameter render
Whether to notify render subscribers. Defaults to
true
Remarks
const x = useMotionValue(0)x.set(10)Modifiers
@public
method setCurrent
setCurrent: (current: V) => void;
method setPrevFrameValue
setPrevFrameValue: (prevFrameValue?: V | undefined) => void;
method setWithVelocity
setWithVelocity: (prev: V, current: V, delta: number) => void;
method stop
stop: () => void;
Stop the currently active animation.
Modifiers
@public
class VisualElement
abstract class VisualElement< Instance = unknown, RenderState = unknown, Options extends {} = {}> {}
A VisualElement is an imperative abstraction around UI elements such as HTMLElement, SVGElement, Three.Object3D etc.
constructor
constructor( { parent, props, presenceContext, reducedMotionConfig, blockInitialAnimation, visualState, }: VisualElementOptions<Instance, RenderState>, options?: {});
property animationState
animationState?: AnimationState$1;
The AnimationState, this is hydrated by the animation Feature.
property blockInitialAnimation
blockInitialAnimation: boolean;
This can be set by AnimatePresence to force components that mount at the same time as it to mount as if they have initial={false} set.
property children
children: Set<VisualElement<unknown, unknown, {}>>;
A set containing references to this VisualElement's children.
property current
current: {};
A reference to the current underlying Instance, e.g. a HTMLElement or Three.Mesh etc.
property depth
depth: number;
The depth of this VisualElement within the overall VisualElement tree.
property isControllingVariants
isControllingVariants: boolean;
property isVariantNode
isVariantNode: boolean;
Determine what role this visual element should take in the variant tree.
property KeyframeResolver
KeyframeResolver: typeof KeyframeResolver;
property latestValues
latestValues: ResolvedValues;
An object containing the latest static values for each of this VisualElement's MotionValues.
property manuallyAnimateOnMount
manuallyAnimateOnMount: boolean;
Normally, if a component is controlled by a parent's variants, it can rely on that ancestor to trigger animations further down the tree. However, if a component is created after its parent is mounted, the parent won't trigger that mount animation so the child needs to.
TODO: This might be better replaced with a method isParentMounted
property notifyUpdate
notifyUpdate: () => void;
property options
readonly options: {};
The options used to create this VisualElement. The Options type is defined by the inheriting VisualElement and is passed straight through to the render functions.
property parent
parent: VisualElement<unknown, unknown, {}>;
A reference to the parent VisualElement (if exists).
property presenceContext
presenceContext: PresenceContextProps;
property prevPresenceContext
prevPresenceContext?: PresenceContextProps;
property prevProps
prevProps?: MotionProps;
property projection
projection?: IProjectionNode<unknown>;
A reference to this VisualElement's projection node, used in layout animations.
property props
props: MotionProps;
A reference to the latest props provided to the VisualElement's host React component.
property render
render: () => void;
property renderState
renderState: {};
The current render state of this VisualElement. Defined by inherting VisualElements.
property scheduleRender
scheduleRender: () => void;
property shouldReduceMotion
shouldReduceMotion: boolean;
Decides whether this VisualElement should animate in reduced motion mode.
TODO: This is currently set on every individual VisualElement but feels like it could be set globally.
property type
abstract type: string;
VisualElements are arranged in trees mirroring that of the React tree. Each type of VisualElement has a unique name, to detect when we're crossing type boundaries within that tree.
property values
values: Map<string, MotionValue<any>>;
A map of all motion values attached to this visual element. Motion values are source of truth for any given animated value. A motion value might be provided externally by the component via props.
property variantChildren
variantChildren?: Set<VisualElement<unknown, unknown, {}>>;
If this component is part of the variant tree, it should track any children that are also part of the tree. This is essentially a shadow tree to simplify logic around how to stagger over children.
method addValue
addValue: (key: string, value: MotionValue) => void;
Add a motion value and bind it to this visual element.
method addVariantChild
addVariantChild: (child: VisualElement) => (() => boolean) | undefined;
Add a child visual element to our set of children.
method build
abstract build: ( renderState: RenderState, latestValues: ResolvedValues, props: MotionProps) => void;
Run before a React or VisualElement render, builds the latest motion values into an Instance-specific format. For example, HTMLVisualElement will use this step to build
style
andvar
values.
method getBaseTarget
getBaseTarget: (key: string) => ResolvedValues[string] | undefined | null;
Find the base target for a value thats been removed from all animation props.
method getBaseTargetFromProps
abstract getBaseTargetFromProps: ( props: MotionProps, key: string) => string | number | undefined | MotionValue;
When a value has been removed from all animation props we need to pick a target to animate back to. For instance, for HTMLElements we can look in the style prop.
method getClosestVariantNode
getClosestVariantNode: () => VisualElement | undefined;
method getDefaultTransition
getDefaultTransition: () => Transition$1 | undefined;
Returns the defined default transition on this component.
method getProps
getProps: () => MotionProps;
method getStaticValue
getStaticValue: (key: string) => string | number;
method getTransformPagePoint
getTransformPagePoint: () => any;
method getValue
getValue: { (key: string): MotionValue | undefined; (key: string, defaultValue: string | number): MotionValue<any>;};
Get a motion value for this key. If called with a default value, we'll create one if none exists.
method getVariant
getVariant: (name: string) => Variant | undefined;
Returns the variant definition with a given name.
method handleChildMotionValue
handleChildMotionValue: () => void;
If the component child is provided as a motion value, handle subscriptions with the renderer-specific VisualElement.
method hasValue
hasValue: (key: string) => boolean;
Check whether we have a motion value for this key
method measureInstanceViewportBox
abstract measureInstanceViewportBox: ( instance: Instance, props: MotionProps & Partial<MotionConfigContext>) => Box;
Measure the viewport-relative bounding box of the Instance.
method measureViewportBox
measureViewportBox: () => Box;
Measure the current viewport box with or without transforms. Only measures axis-aligned boxes, rotate and skew must be manually removed with a re-render to work.
method mount
mount: (instance: Instance) => void;
method notify
notify: <EventName extends keyof VisualElementEventCallbacks>( eventName: EventName, ...args: any) => void;
method on
on: <EventName extends keyof VisualElementEventCallbacks>( eventName: EventName, callback: VisualElementEventCallbacks[EventName]) => VoidFunction;
method readValue
readValue: (key: string, target?: string | number | null) => any;
If we're trying to animate to a previously unencountered value, we need to check for it in our state and as a last resort read it directly from the instance (which might have performance implications).
method readValueFromInstance
abstract readValueFromInstance: ( instance: Instance, key: string, options: Options) => string | number | null | undefined;
When we first animate to a value we need to animate it *from* a value. Often this have been specified via the initial prop but it might be that the value needs to be read from the Instance.
method removeValue
removeValue: (key: string) => void;
Remove a motion value and unbind any active subscriptions.
method removeValueFromRenderState
abstract removeValueFromRenderState: ( key: string, renderState: RenderState) => void;
When a value has been removed from the VisualElement we use this to remove it from the inherting class' unique render state.
method renderInstance
abstract renderInstance: ( instance: Instance, renderState: RenderState, styleProp?: MotionStyle, projection?: IProjectionNode) => void;
Apply the built values to the Instance. For example, HTMLElements will have styles applied via
setProperty
and the style attribute, whereas SVGElements will have values applied to attributes.
method scrapeMotionValuesFromProps
scrapeMotionValuesFromProps: ( _props: MotionProps, _prevProps: MotionProps, _visualElement: VisualElement) => { [key: string]: string | number | MotionValue<any> };
This method takes React props and returns found MotionValues. For example, HTML MotionValues will be found within the style prop, whereas for Three.js within attribute arrays.
This isn't an abstract method as it needs calling in the constructor, but it is intended to be one.
method setBaseTarget
setBaseTarget: (key: string, value: string | number) => void;
Set the base target to later animate back to. This is currently only hydrated on creation and when we first read a value.
method setStaticValue
setStaticValue: (key: string, value: string | number) => void;
method sortInstanceNodePosition
abstract sortInstanceNodePosition: (a: Instance, b: Instance) => number;
An
Array.sort
compatible function that will compare two Instances and compare their respective positions within the tree.
method sortNodePosition
sortNodePosition: (other: VisualElement<Instance>) => number;
method triggerBuild
triggerBuild: () => void;
method unmount
unmount: () => void;
method update
update: ( props: MotionProps, presenceContext: PresenceContextProps | null) => void;
Update the provided props. Ensure any newly-added motion values are added to our map, old ones removed, and listeners updated.
method updateFeatures
updateFeatures: () => void;
Interfaces
interface AbsoluteKeyframe
interface AbsoluteKeyframe {}
interface AnimatePresenceProps
interface AnimatePresenceProps {}
Modifiers
@public
property custom
custom?: any;
When a component is removed, there's no longer a chance to update its props. So if a component's
exit
prop is defined as a dynamic variant and you want to pass a newcustom
prop, you can do so viaAnimatePresence
. This will ensure all leaving components animate using the latest data.Modifiers
@public
property exitBeforeEnter
exitBeforeEnter?: boolean;
Replace with
mode="wait"
Deprecated
Replace with
mode="wait"
property initial
initial?: boolean;
By passing
initial={false}
,AnimatePresence
will disable any initial animations on children that are present when the component is first rendered.<AnimatePresence initial={false}>{isVisible && (<motion.divkey="modal"initial={{ opacity: 0 }}animate={{ opacity: 1 }}exit={{ opacity: 0 }}/>)}</AnimatePresence>Modifiers
@public
property mode
mode?: 'sync' | 'popLayout' | 'wait';
Determines how to handle entering and exiting elements.
-
"sync"
: Default. Elements animate in and out as soon as they're added/removed. -"popLayout"
: Exiting elements are "popped" from the page layout, allowing sibling elements to immediately occupy their new layouts. -"wait"
: Only renders one component at a time. Wait for the exiting component to animate out before animating the next component in.Modifiers
@public
property onExitComplete
onExitComplete?: () => void;
Fires when all exiting nodes have completed animating out.
Modifiers
@public
property presenceAffectsLayout
presenceAffectsLayout?: boolean;
Internal. Used in Framer to flag that sibling children *shouldn't* re-render as a result of a child being removed.
interface AnimationControls
interface AnimationControls {}
Modifiers
@public
method mount
mount: () => () => void;
method set
set: (definition: AnimationDefinition) => void;
Instantly set to a set of properties or a variant.
// With propertiescontrols.set({ opacity: 0 })// With variantscontrols.set("hidden")Modifiers
@public
method start
start: ( definition: AnimationDefinition, transitionOverride?: Transition) => Promise<any>;
Starts an animation on all linked components.
Parameter definition
Properties or variant label to animate to
Parameter transition
Optional
transtion
to apply to a variantReturns
- A
Promise
that resolves when all animations have completed.Remarks
controls.start("variantLabel")controls.start({x: 0,transition: { duration: 1 }})Modifiers
@public
method stop
stop: () => void;
Stops animations on all linked components.
controls.stop()Modifiers
@public
interface AnimationLifecycles
interface AnimationLifecycles {}
method onAnimationComplete
onAnimationComplete: (definition: AnimationDefinition) => void;
Callback when animation defined in
animate
is complete.The provided callback will be called with the triggering animation definition. If this is a variant, it'll be the variant name, and if a target object then it'll be the target object.
This way, it's possible to figure out which animation has completed.
function onComplete() {console.log("Animation completed")}<motion.divanimate={{ x: 100 }}onAnimationComplete={definition => {console.log('Completed animating', definition)}}/>
method onAnimationStart
onAnimationStart: (definition: AnimationDefinition) => void;
Callback when animation defined in
animate
begins.The provided callback will be called with the triggering animation definition. If this is a variant, it'll be the variant name, and if a target object then it'll be the target object.
This way, it's possible to figure out which animation has started.
function onStart() {console.log("Animation started")}<motion.div animate={{ x: 100 }} onAnimationStart={onStart} />
method onUpdate
onUpdate: (latest: ResolvedValues) => void;
Callback with latest motion values, fired max once per frame.
function onUpdate(latest) {console.log(latest.x, latest.opacity)}<motion.div animate={{ x: 100, opacity: 0 }} onUpdate={onUpdate} />
interface AnimationPlaybackControls
interface AnimationPlaybackControls {}
Modifiers
@public
property attachTimeline
attachTimeline?: ( timeline: ProgressTimeline, fallback?: (animation: AnimationPlaybackControls) => VoidFunction) => VoidFunction;
property cancel
cancel: () => void;
property complete
complete: () => void;
property duration
duration: number;
property flatten
flatten: () => void;
property pause
pause: () => void;
property play
play: () => void;
property speed
speed: number;
property startTime
startTime: number | null;
property state
state?: AnimationPlayState;
property stop
stop: () => void;
property then
then: (onResolve: VoidFunction, onReject?: VoidFunction) => Promise<void>;
property time
time: number;
interface AnimationPlaybackLifecycles
interface AnimationPlaybackLifecycles<V> {}
property onComplete
onComplete?: () => void;
property onPlay
onPlay?: () => void;
property onRepeat
onRepeat?: () => void;
property onStop
onStop?: () => void;
property onUpdate
onUpdate?: (latest: V) => void;
interface AnimationPlaybackOptions
interface AnimationPlaybackOptions {}
property repeat
repeat?: number;
property repeatDelay
repeatDelay?: number;
property repeatType
repeatType?: RepeatType;
interface AnimationProps
interface AnimationProps {}
Modifiers
@public
property animate
animate?: AnimationControls | TargetAndTransition | VariantLabels | boolean;
Values to animate to, variant label(s), or
AnimationControls
.// As values<motion.div animate={{ opacity: 1 }} />// As variant<motion.div animate="visible" variants={variants} />// Multiple variants<motion.div animate={["visible", "active"]} variants={variants} />// AnimationControls<motion.div animate={animation} />
property exit
exit?: TargetAndTransition | VariantLabels;
A target to animate to when this component is removed from the tree.
This component **must** be the first animatable child of an
AnimatePresence
to enable this exit animation.This limitation exists because React doesn't allow components to defer unmounting until after an animation is complete. Once this limitation is fixed, the
AnimatePresence
component will be unnecessary.import { AnimatePresence, motion } from 'framer-motion'export const MyComponent = ({ isVisible }) => {return (<AnimatePresence>{isVisible && (<motion.divinitial={{ opacity: 0 }}animate={{ opacity: 1 }}exit={{ opacity: 0 }}/>)}</AnimatePresence>)}
property initial
initial?: boolean | Target | VariantLabels;
Properties, variant label or array of variant labels to start in.
Set to
false
to initialise with the values inanimate
(disabling the mount animation)// As values<motion.div initial={{ opacity: 1 }} />// As variant<motion.div initial="visible" variants={variants} />// Multiple variants<motion.div initial={["visible", "active"]} variants={variants} />// As false (disable mount animation)<motion.div initial={false} animate={{ opacity: 0 }} />
property transition
transition?: Transition$1;
Default transition. If no
transition
is defined inanimate
, it will use the transition defined here.const spring = {type: "spring",damping: 10,stiffness: 100}<motion.div transition={spring} animate={{ scale: 1.2 }} />
property variants
variants?: Variants;
Variants allow you to define animation states and organise them by name. They allow you to control animations throughout a component tree by switching a single
animate
prop.Using
transition
options likedelayChildren
andstaggerChildren
, you can orchestrate when children animations play relative to their parent.After passing variants to one or more
motion
component'svariants
prop, these variants can be used in place of values on theanimate
,initial
,whileFocus
,whileTap
andwhileHover
props.const variants = {active: {backgroundColor: "#f00"},inactive: {backgroundColor: "#fff",transition: { duration: 2 }}}<motion.div variants={variants} animate="active" />
interface AxisDelta
interface AxisDelta {}
property origin
origin: number;
property originPoint
originPoint: number;
property scale
scale: number;
property translate
translate: number;
interface BoundingBox
interface BoundingBox {}
interface CSSStyleDeclarationWithTransform
interface CSSStyleDeclarationWithTransform extends Omit< CSSStyleDeclaration, 'direction' | 'transition' | 'x' | 'y' | 'z' > {}
property rotateX
rotateX: number | string;
property rotateY
rotateY: number | string;
property rotateZ
rotateZ: number | string;
property scaleX
scaleX: number;
property scaleY
scaleY: number;
property scaleZ
scaleZ: number;
property skewX
skewX: number | string;
property skewY
skewY: number | string;
property x
x: number | string;
property y
y: number | string;
property z
z: number | string;
interface CustomValueType
interface CustomValueType {}
Modifiers
@public
interface DecayOptions
interface DecayOptions extends VelocityOptions {}
property keyframes
keyframes?: number[];
property modifyTarget
modifyTarget?: (v: number) => number;
property power
power?: number;
property timeConstant
timeConstant?: number;
interface DraggableProps
interface DraggableProps extends DragHandlers {}
Modifiers
@public
property drag
drag?: boolean | 'x' | 'y';
Enable dragging for this element. Set to
false
by default. Settrue
to drag in both directions. Set"x"
or"y"
to only drag in a specific direction.<motion.div drag="x" />
property dragConstraints
dragConstraints?: false | Partial<BoundingBox> | RefObject<Element | null>;
Applies constraints on the permitted draggable area.
It can accept an object of optional
top
,left
,right
, andbottom
values, measured in pixels. This will define a distance the named edge of the draggable component.Alternatively, it can accept a
ref
to another component created with React'suseRef
hook. Thisref
should be passed both to the draggable component'sdragConstraints
prop, and theref
of the component you want to use as constraints.// In pixels<motion.divdrag="x"dragConstraints={{ left: 0, right: 300 }}/>// As a ref to another componentconst MyComponent = () => {const constraintsRef = useRef(null)return (<motion.div ref={constraintsRef}><motion.div drag dragConstraints={constraintsRef} /></motion.div>)}
property dragControls
dragControls?: DragControls;
Usually, dragging is initiated by pressing down on a component and moving it. For some use-cases, for instance clicking at an arbitrary point on a video scrubber, we might want to initiate dragging from a different component than the draggable one.
By creating a
dragControls
using theuseDragControls
hook, we can pass this into the draggable component'sdragControls
prop. It exposes astart
method that can start dragging from pointer events on other components.const dragControls = useDragControls()function startDrag(event) {dragControls.start(event, { snapToCursor: true })}return (<><div onPointerDown={startDrag} /><motion.div drag="x" dragControls={dragControls} /></>)
property dragDirectionLock
dragDirectionLock?: boolean;
If
true
, this will lock dragging to the initially-detected direction. Defaults tofalse
.<motion.div drag dragDirectionLock />
property dragElastic
dragElastic?: DragElastic;
The degree of movement allowed outside constraints. 0 = no movement, 1 = full movement.
Set to
0.5
by default. Can also be set asfalse
to disable movement.By passing an object of
top
/right
/bottom
/left
, individual values can be set per constraint. Any missing values will be set to0
.<motion.divdragdragConstraints={{ left: 0, right: 300 }}dragElastic={0.2}/>
property dragListener
dragListener?: boolean;
By default, if
drag
is defined on a component then an event listener will be attached to automatically initiate dragging when a user presses down on it.By setting
dragListener
tofalse
, this event listener will not be created.const dragControls = useDragControls()function startDrag(event) {dragControls.start(event, { snapToCursor: true })}return (<><div onPointerDown={startDrag} /><motion.divdrag="x"dragControls={dragControls}dragListener={false}/></>)
property dragMomentum
dragMomentum?: boolean;
Apply momentum from the pan gesture to the component when dragging finishes. Set to
true
by default.<motion.divdragdragConstraints={{ left: 0, right: 300 }}dragMomentum={false}/>
property dragPropagation
dragPropagation?: boolean;
Allows drag gesture propagation to child components. Set to
false
by default.<motion.div drag="x" dragPropagation />
property dragSnapToOrigin
dragSnapToOrigin?: boolean;
If true, element will snap back to its origin when dragging ends.
Enabling this is the equivalent of setting all
dragConstraints
axes to0
withdragElastic={1}
, but when used togetherdragConstraints
can define a wider draggable area anddragSnapToOrigin
will ensure the element animates back to its origin on release.
property dragTransition
dragTransition?: InertiaOptions;
Allows you to change dragging inertia parameters. When releasing a draggable Frame, an animation with type
inertia
starts. The animation is based on your dragging velocity. This property allows you to customize it. See Inertia for all properties you can use.<motion.divdragdragTransition={{ bounceStiffness: 600, bounceDamping: 10 }}/>
property onMeasureDragConstraints
onMeasureDragConstraints?: (constraints: BoundingBox) => BoundingBox | void;
If
dragConstraints
is set to a React ref, this callback will call with the measured drag constraints.Modifiers
@public
property whileDrag
whileDrag?: VariantLabels | TargetAndTransition;
Properties or variant label to animate to while the drag gesture is recognised.
<motion.div whileDrag={{ scale: 1.2 }} />
interface DragHandlers
interface DragHandlers {}
Modifiers
@public
method onDirectionLock
onDirectionLock: (axis: 'x' | 'y') => void;
Callback function that fires a drag direction is determined.
<motion.divdragdragDirectionLockonDirectionLock={axis => console.log(axis)}/>Modifiers
@public
method onDrag
onDrag: (event: MouseEvent | TouchEvent | PointerEvent, info: PanInfo) => void;
Callback function that fires when the component is dragged.
<motion.divdragonDrag={(event, info) => console.log(info.point.x, info.point.y)}/>Modifiers
@public
method onDragEnd
onDragEnd: ( event: MouseEvent | TouchEvent | PointerEvent, info: PanInfo) => void;
Callback function that fires when dragging ends.
<motion.divdragonDragEnd={(event, info) => console.log(info.point.x, info.point.y)}/>Modifiers
@public
method onDragStart
onDragStart: ( event: MouseEvent | TouchEvent | PointerEvent, info: PanInfo) => void;
Callback function that fires when dragging starts.
<motion.divdragonDragStart={(event, info) => console.log(info.point.x, info.point.y)}/>Modifiers
@public
method onDragTransitionEnd
onDragTransitionEnd: () => void;
Callback function that fires when drag momentum/bounce transition finishes.
<motion.divdragonDragTransitionEnd={() => console.log('Drag transition complete')}/>Modifiers
@public
interface DurationSpringOptions
interface DurationSpringOptions {}
property bounce
bounce?: number;
property duration
duration?: number;
property visualDuration
visualDuration?: number;
interface DynamicAnimationOptions
interface DynamicAnimationOptions extends Omit<AnimationOptionsWithValueOverrides, 'delay'> {}
property delay
delay?: number | DynamicOption<number>;
interface FeatureBundle
interface FeatureBundle extends FeaturePackages {}
property renderer
renderer: CreateVisualElement<any>;
interface FocusHandlers
interface FocusHandlers {}
Modifiers
@public
property whileFocus
whileFocus?: VariantLabels | TargetAndTransition;
Properties or variant label to animate to while the focus gesture is recognised.
<motion.input whileFocus={{ scale: 1.2 }} />
interface HoverHandlers
interface HoverHandlers {}
Modifiers
@public
property whileHover
whileHover?: VariantLabels | TargetAndTransition;
Properties or variant label to animate to while the hover gesture is recognised.
<motion.div whileHover={{ scale: 1.2 }} />
method onHoverEnd
onHoverEnd: (event: MouseEvent, info: EventInfo) => void;
Callback function that fires when pointer stops hovering over the component.
<motion.div onHoverEnd={() => console.log("Hover ends")} />
method onHoverStart
onHoverStart: (event: MouseEvent, info: EventInfo) => void;
Callback function that fires when pointer starts hovering over the component.
<motion.div onHoverStart={() => console.log('Hover starts')} />
interface HydratedFeatureDefinitions
interface HydratedFeatureDefinitions {}
property animation
animation?: HydratedFeatureDefinition;
property drag
drag?: HydratedFeatureDefinition;
property exit
exit?: HydratedFeatureDefinition;
property focus
focus?: HydratedFeatureDefinition;
property hover
hover?: HydratedFeatureDefinition;
property inView
inView?: HydratedFeatureDefinition;
property layout
layout?: HydratedFeatureDefinition;
property pan
pan?: HydratedFeatureDefinition;
property tap
tap?: HydratedFeatureDefinition;
interface Inertia
interface Inertia {}
An animation that decelerates a value based on its initial velocity, usually used to implement inertial scrolling.
Optionally,
min
andmax
boundaries can be defined, and inertia will snap to these with a spring animation.This animation will automatically precalculate a target value, which can be modified with the
modifyTarget
property.This allows you to add snap-to-grid or similar functionality.
Inertia is also the animation used for
dragTransition
, and can be configured via that prop.Modifiers
@public
property bounceDamping
bounceDamping?: number;
If
min
ormax
is set, this affects the damping of the bounce spring. If set to0
, spring will oscillate indefinitely. Set to10
by default.<motion.divdragdragTransition={{min: 0,max: 100,bounceDamping: 8}}/>Modifiers
@public
property bounceStiffness
bounceStiffness?: number;
If
min
ormax
is set, this affects the stiffness of the bounce spring. Higher values will create more sudden movement. Set to500
by default.<motion.divdragdragTransition={{min: 0,max: 100,bounceStiffness: 100}}/>Modifiers
@public
property from
from?: number | string;
The value to animate from. By default, this is the current state of the animating value.
<FramedragdragTransition={{ from: 50 }}/>Modifiers
@public
property max
max?: number;
Maximum constraint. If set, the value will "bump" against this value (or immediately snap to it, if the initial animation value exceeds this value).
<motion.divdragdragTransition={{ min: 0, max: 100 }}/>Modifiers
@public
property min
min?: number;
Minimum constraint. If set, the value will "bump" against this value (or immediately spring to it if the animation starts as less than this value).
<motion.divdragdragTransition={{ min: 0, max: 100 }}/>Modifiers
@public
property power
power?: number;
A higher power value equals a further target. Set to
0.8
by default.<motion.divdragdragTransition={{ power: 0.2 }}/>Modifiers
@public
property restDelta
restDelta?: number;
End the animation if the distance to the animation target is below this value, and the absolute speed is below
restSpeed
. When the animation ends, the value gets snapped to the animation target. Set to0.01
by default. Generally the default values provide smooth animation endings, only in rare cases should you need to customize these.<motion.divdragdragTransition={{ restDelta: 10 }}/>Modifiers
@public
property timeConstant
timeConstant?: number;
Adjusting the time constant will change the duration of the deceleration, thereby affecting its feel. Set to
700
by default.<motion.divdragdragTransition={{ timeConstant: 200 }}/>Modifiers
@public
property type
type: 'inertia';
Set
type
to animate using the inertia animation. Set to"tween"
by default. This can be used for natural deceleration, like momentum scrolling.<motion.divanimate={{ rotate: 180 }}transition={{ type: "inertia", velocity: 50 }}/>Modifiers
@public
property velocity
velocity?: number;
The initial velocity of the animation. By default this is the current velocity of the component.
<motion.divanimate={{ rotate: 180 }}transition={{ type: 'inertia', velocity: 200 }}/>Modifiers
@public
method modifyTarget
modifyTarget: (v: number) => number;
A function that receives the automatically-calculated target and returns a new one. Useful for snapping the target to a grid.
<motion.divdragdragTransition={{power: 0,// Snap calculated target to nearest 50 pixelsmodifyTarget: target => Math.round(target / 50) * 50}}/>Modifiers
@public
interface InertiaOptions
interface InertiaOptions$1 extends DecayOptions {}
property bounceDamping
bounceDamping?: number;
property bounceStiffness
bounceStiffness?: number;
property max
max?: number;
property min
min?: number;
interface InterpolateOptions
interface InterpolateOptions<T> {}
interface IProjectionNode
interface IProjectionNode<I = unknown> {}
property animationId
animationId: number;
property animationValues
animationValues?: ResolvedValues;
property children
children: Set<IProjectionNode>;
property currentAnimation
currentAnimation?: AnimationPlaybackControls;
property depth
depth: number;
property hasCheckedOptimisedAppear
hasCheckedOptimisedAppear: boolean;
property hasTreeAnimated
hasTreeAnimated: boolean;
property id
id: number;
property instance
instance: I;
property isAnimationBlocked
isAnimationBlocked?: boolean;
property isLayoutDirty
isLayoutDirty: boolean;
property isPresent
isPresent?: boolean;
property isProjectionDirty
isProjectionDirty: boolean;
property isSharedProjectionDirty
isSharedProjectionDirty: boolean;
property isTransformDirty
isTransformDirty: boolean;
property isTreeAnimating
isTreeAnimating?: boolean;
property isTreeAnimationBlocked
isTreeAnimationBlocked: () => boolean;
property isUpdating
isUpdating: boolean;
property isVisible
isVisible: boolean;
property latestValues
latestValues: ResolvedValues;
property layout
layout?: Measurements;
property mount
mount: (node: I, isLayoutDirty?: boolean) => void;
property needsReset
needsReset: boolean;
property nodes
nodes?: FlatTree;
property options
options: ProjectionNodeOptions;
property parent
parent?: IProjectionNode;
property path
path: IProjectionNode[];
property preserveOpacity
preserveOpacity?: boolean;
property prevTransformTemplateValue
prevTransformTemplateValue: string | undefined;
property projectionDelta
projectionDelta?: Delta;
property projectionDeltaWithTransform
projectionDeltaWithTransform?: Delta;
property relativeParent
relativeParent?: IProjectionNode;
property relativeTarget
relativeTarget?: Box;
property relativeTargetOrigin
relativeTargetOrigin?: Box;
property resolvedRelativeTargetAt
resolvedRelativeTargetAt?: number;
property resumeFrom
resumeFrom?: IProjectionNode;
property resumingFrom
resumingFrom?: IProjectionNode;
property root
root?: IProjectionNode;
property scroll
scroll?: ScrollMeasurements;
property sharedNodes
sharedNodes: Map<string, NodeStack>;
property shouldResetTransform
shouldResetTransform: boolean;
property snapshot
snapshot?: Measurements;
property target
target?: Box;
property targetDelta
targetDelta?: Delta;
property targetWithTransforms
targetWithTransforms?: Box;
property treeScale
treeScale?: Point;
property unmount
unmount: () => void;
property updateBlockedByResize
updateBlockedByResize: boolean;
property updateManuallyBlocked
updateManuallyBlocked: boolean;
method addEventListener
addEventListener: (name: LayoutEvents, handler: any) => VoidFunction;
method applyTransform
applyTransform: (box: Box, transformOnly?: boolean) => Box;
method blockUpdate
blockUpdate: () => void;
method calcProjection
calcProjection: () => void;
method checkUpdateFailed
checkUpdateFailed: () => void;
method clearMeasurements
clearMeasurements: () => void;
method clearSnapshot
clearSnapshot: () => void;
method didUpdate
didUpdate: () => void;
method finishAnimation
finishAnimation: () => void;
method getClosestProjectingParent
getClosestProjectingParent: () => IProjectionNode | undefined;
method getProjectionStyles
getProjectionStyles: (styleProp?: MotionStyle) => MotionStyle | undefined;
method getStack
getStack: () => NodeStack | undefined;
method hasListeners
hasListeners: (name: LayoutEvents) => boolean;
method hide
hide: () => void;
method isLead
isLead: () => boolean;
method isProjecting
isProjecting: () => boolean;
method isUpdateBlocked
isUpdateBlocked: () => boolean;
method measure
measure: (removeTransform?: boolean) => Measurements;
method measurePageBox
measurePageBox: () => Box;
method notifyListeners
notifyListeners: (name: LayoutEvents, ...args: any) => void;
method promote
promote: (options?: { needsReset?: boolean; transition?: Transition$1; preserveFollowOpacity?: boolean;}) => void;
method registerSharedNode
registerSharedNode: (id: string, node: IProjectionNode) => void;
method relegate
relegate: () => boolean;
method resetSkewAndRotation
resetSkewAndRotation: () => void;
method resetTransform
resetTransform: () => void;
method resetTree
resetTree: () => void;
method resolveTargetDelta
resolveTargetDelta: (force?: boolean) => void;
method scheduleCheckAfterUnmount
scheduleCheckAfterUnmount: () => void;
method scheduleRender
scheduleRender: (notifyAll?: boolean) => void;
method scheduleUpdateProjection
scheduleUpdateProjection: () => void;
method setAnimationOrigin
setAnimationOrigin: (delta: Delta) => void;
method setOptions
setOptions: (options: ProjectionNodeOptions) => void;
method setTargetDelta
setTargetDelta: (delta: Delta) => void;
method show
show: () => void;
method startAnimation
startAnimation: (transition: Transition$1) => void;
method startUpdate
startUpdate: () => void;
method unblockUpdate
unblockUpdate: () => void;
method updateLayout
updateLayout: () => void;
method updateScroll
updateScroll: (phase?: Phase) => void;
method updateSnapshot
updateSnapshot: () => void;
method willUpdate
willUpdate: (notifyListeners?: boolean) => void;
interface KeyframeOptions
interface KeyframeOptions {}
interface Keyframes
interface Keyframes {}
Keyframes tweens between multiple
values
.These tweens can be arranged using the
duration
,easings
, andtimes
properties.
property duration
duration?: number;
The total duration of the animation. Set to
0.3
by default.const transition = {type: "keyframes",duration: 2}<Frameanimate={{ opacity: 0 }}transition={transition}/>Modifiers
@public
property ease
ease?: Easing | Easing[];
An array of easing functions for each generated tween, or a single easing function applied to all tweens.
This array should be one item less than
values
, as these easings apply to the transitions *between* thevalues
.const transition = {backgroundColor: {type: 'keyframes',easings: ['circIn', 'circOut']}}Modifiers
@public
property repeatDelay
repeatDelay?: number;
Modifiers
@public
property times
times?: number[];
An array of numbers between 0 and 1, where
1
represents thetotal
duration.Each value represents at which point during the animation each item in the animation target should be hit, so the array should be the same length as
values
.Defaults to an array of evenly-spread durations.
Modifiers
@public
property type
type: 'keyframes';
Set
type
to"keyframes"
to animate using the keyframes animation. Set to"tween"
by default. This can be used to animate between a series of values.Modifiers
@public
interface LayoutProps
interface LayoutProps {}
Modifiers
@public
property "data-framer-portal-id"
'data-framer-portal-id'?: string;
Attached to a portal root to ensure we attach the child to the document root and don't perform scale correction on it.
property layout
layout?: boolean | 'position' | 'size' | 'preserve-aspect';
If
true
, this component will automatically animate to its new position when its layout changes.<motion.div layout />This will perform a layout animation using performant transforms. Part of this technique involved animating an element's scale. This can introduce visual distortions on children,
boxShadow
andborderRadius
.To correct distortion on immediate children, add
layout
to those too.boxShadow
andborderRadius
will automatically be corrected if they are already being animated on this component. Otherwise, set them directly via theinitial
prop.If
layout
is set to"position"
, the size of the component will change instantly and only its position will animate.If
layout
is set to"size"
, the position of the component will change instantly and only its size will animate.If
layout
is set to"preserve-aspect"
, the component will animate size & position if the aspect ratio remains the same between renders, and just position if the ratio changes.Modifiers
@public
property layoutDependency
layoutDependency?: any;
Modifiers
@public
property layoutId
layoutId?: string;
Enable shared layout transitions between different components with the same
layoutId
.When a component with a layoutId is removed from the React tree, and then added elsewhere, it will visually animate from the previous component's bounding box and its latest animated values.
{items.map(item => (<motion.li layout>{item.name}{item.isSelected && <motion.div layoutId="underline" />}</motion.li>))}If the previous component remains in the tree it will crossfade with the new component.
Modifiers
@public
property layoutRoot
layoutRoot?: boolean;
Whether an element should be considered a "layout root", where all children will be forced to resolve relatively to it. Currently used for
position: sticky
elements in Framer.
property layoutScroll
layoutScroll?: boolean;
Whether a projection node should measure its scroll when it or its descendants update their layout.
Modifiers
@public
method onLayoutAnimationComplete
onLayoutAnimationComplete: () => void;
A callback that will fire when a layout animation on this component completes.
Modifiers
@public
method onLayoutAnimationStart
onLayoutAnimationStart: () => void;
A callback that will fire when a layout animation on this component starts.
Modifiers
@public
interface LazyProps
interface LazyProps {}
Modifiers
@public
property children
children?: React.ReactNode;
property features
features: FeatureBundle | LazyFeatureBundle;
Can be used to provide a feature bundle synchronously or asynchronously.
// features.jsimport { domAnimation } from "framer-motion"export default domAnimation// index.jsimport { LazyMotion, m } from "framer-motion"const loadFeatures = import("./features.js").then(res => res.default)function Component() {return (<LazyMotion features={loadFeatures}><m.div animate={{ scale: 1.5 }} /></LazyMotion>)}Modifiers
@public
property strict
strict?: boolean;
If
true
, will throw an error if amotion
component renders within aLazyMotion
component.// This component will throw an error that explains using a motion component// instead of the m component will break the benefits of code-splitting.function Component() {return (<LazyMotion features={domAnimation} strict><motion.div /></LazyMotion>)}Modifiers
@public
interface MotionAdvancedProps
interface MotionAdvancedProps {}
Modifiers
@public
property custom
custom?: any;
Custom data to use to resolve dynamic variants differently for each animating component.
const variants = {visible: (custom) => ({opacity: 1,transition: { delay: custom * 0.2 }})}<motion.div custom={0} animate="visible" variants={variants} /><motion.div custom={1} animate="visible" variants={variants} /><motion.div custom={2} animate="visible" variants={variants} />Modifiers
@public
property ignoreStrict
ignoreStrict?: boolean;
Set to
false
to prevent throwing an error when amotion
component is used within aLazyMotion
set to strict.Modifiers
@public
property inherit
inherit?: boolean;
Set to
false
to prevent inheriting variant changes from its parent.Modifiers
@public
interface MotionConfigContext
interface MotionConfigContext {}
Modifiers
@public
property isStatic
isStatic: boolean;
Internal. Determines whether this is a static context ie the Framer canvas. If so, it'll disable all dynamic functionality.
property nonce
nonce?: string;
A custom
nonce
attribute used when wanting to enforce a Content Security Policy (CSP). For more details see: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/style-src#unsafe_inline_stylesModifiers
@public
property reducedMotion
reducedMotion?: ReducedMotionConfig;
If true, will respect the device prefersReducedMotion setting by switching transform animations off.
Modifiers
@public
property transformPagePoint
transformPagePoint: TransformPoint;
Internal, exported only for usage in Framer
property transition
transition?: Transition$1;
Defines a new default transition for the entire tree.
Modifiers
@public
interface MotionConfigProps
interface MotionConfigProps extends Partial<MotionConfigContext> {}
property children
children?: React$1.ReactNode;
property isValidProp
isValidProp?: IsValidProp;
interface MotionProps
interface MotionProps extends AnimationProps, EventProps, PanHandlers, TapHandlers, HoverHandlers, FocusHandlers, ViewportProps, DraggableProps, LayoutProps, MotionAdvancedProps {}
Props for
motion
components.Modifiers
@public
property "data-framer-appear-id"
'data-framer-appear-id'?: string;
property children
children?: React.ReactNode | MotionValue<number> | MotionValue<string>;
property style
style?: MotionStyle;
The React DOM
style
prop, enhanced with support forMotionValue
s and separatetransform
values.export const MyComponent = () => {const x = useMotionValue(0)return <motion.div style={{ x, opacity: 1, scale: 0.5 }} />}
method transformTemplate
transformTemplate: ( transform: TransformProperties, generatedTransform: string) => string;
By default, Motion generates a
transform
property with a sensible transform order.transformTemplate
can be used to create a different order, or to append/preprend the automatically generatedtransform
property.<motion.divstyle={{ x: 0, rotate: 180 }}transformTemplate={({ x, rotate }) => `rotate(${rotate}deg) translateX(${x}px)`}/>Parameter transform
The latest animated transform props.
Parameter generatedTransform
The transform string as automatically generated by Motion
Modifiers
@public
interface None
interface None {}
Modifiers
@public
property type
type: false;
Set
type
tofalse
for an instant transition.Modifiers
@public
interface Orchestration
interface Orchestration {}
Options for orchestrating the timing of animations.
Modifiers
@public
property delay
delay?: number;
Delay the animation by this duration (in seconds). Defaults to
0
.Remarks
const transition = {delay: 0.2}Modifiers
@public
property delayChildren
delayChildren?: number;
When using variants, children animations will start after this duration (in seconds). You can add the
transition
property to both theFrame
and thevariant
directly. Adding it to thevariant
generally offers more flexibility, as it allows you to customize the delay per visual state.const container = {hidden: { opacity: 0 },show: {opacity: 1,transition: {delayChildren: 0.5}}}const item = {hidden: { opacity: 0 },show: { opacity: 1 }}return (<motion.ulvariants={container}initial="hidden"animate="show"><motion.li variants={item} /><motion.li variants={item} /></motion.ul>)Modifiers
@public
property staggerChildren
staggerChildren?: number;
When using variants, animations of child components can be staggered by this duration (in seconds).
For instance, if
staggerChildren
is0.01
, the first child will be delayed by0
seconds, the second by0.01
, the third by0.02
and so on.The calculated stagger delay will be added to
delayChildren
.const container = {hidden: { opacity: 0 },show: {opacity: 1,transition: {staggerChildren: 0.5}}}const item = {hidden: { opacity: 0 },show: { opacity: 1 }}return (<motion.olvariants={container}initial="hidden"animate="show"><motion.li variants={item} /><motion.li variants={item} /></motion.ol>)Modifiers
@public
property staggerDirection
staggerDirection?: number;
The direction in which to stagger children.
A value of
1
staggers from the first to the last while-1
staggers from the last to the first.const container = {hidden: { opacity: 0 },show: {opacity: 1,transition: {staggerChildren: 0.5,staggerDirection: -1}}}const item = {hidden: { opacity: 0 },show: { opacity: 1 }}return (<motion.ulvariants={container}initial="hidden"animate="show"><motion.li variants={item} size={50} /><motion.li variants={item} size={50} /></motion.ul>)Modifiers
@public
property when
when?: false | 'beforeChildren' | 'afterChildren' | string;
Describes the relationship between the transition and its children. Set to
false
by default.Remarks
When using variants, the transition can be scheduled in relation to its children with either
"beforeChildren"
to finish this transition before starting children transitions,"afterChildren"
to finish children transitions before starting this transition.const list = {hidden: {opacity: 0,transition: { when: "afterChildren" }}}const item = {hidden: {opacity: 0,transition: { duration: 2 }}}return (<motion.ul variants={list} animate="hidden"><motion.li variants={item} /><motion.li variants={item} /></motion.ul>)Modifiers
@public
interface PanHandlers
interface PanHandlers {}
Modifiers
@public
method onPan
onPan: (event: PointerEvent, info: PanInfo) => void;
Callback function that fires when the pan gesture is recognised on this element.
**Note:** For pan gestures to work correctly with touch input, the element needs touch scrolling to be disabled on either x/y or both axis with the [touch-action](https://developer.mozilla.org/en-US/docs/Web/CSS/touch-action) CSS rule.
function onPan(event, info) {console.log(info.point.x, info.point.y)}<motion.div onPan={onPan} />Parameter event
The originating pointer event.
Parameter info
A PanInfo object containing
x
andy
values for:-
point
: Relative to the device or page. -delta
: Distance moved since the last event. -offset
: Offset from the original pan event. -velocity
: Current velocity of the pointer.
method onPanEnd
onPanEnd: (event: PointerEvent, info: PanInfo) => void;
Callback function that fires when the pan gesture ends on this element.
function onPanEnd(event, info) {console.log(info.point.x, info.point.y)}<motion.div onPanEnd={onPanEnd} />Parameter event
The originating pointer event.
Parameter info
A PanInfo object containing
x
/y
values for:-
point
: Relative to the device or page. -delta
: Distance moved since the last event. -offset
: Offset from the original pan event. -velocity
: Current velocity of the pointer.
method onPanSessionStart
onPanSessionStart: (event: PointerEvent, info: EventInfo) => void;
Callback function that fires when we begin detecting a pan gesture. This is analogous to
onMouseStart
oronTouchStart
.function onPanSessionStart(event, info) {console.log(info.point.x, info.point.y)}<motion.div onPanSessionStart={onPanSessionStart} />Parameter event
The originating pointer event.
Parameter info
An EventInfo object containing
x
/y
values for:-
point
: Relative to the device or page.
method onPanStart
onPanStart: (event: PointerEvent, info: PanInfo) => void;
Callback function that fires when the pan gesture begins on this element.
function onPanStart(event, info) {console.log(info.point.x, info.point.y)}<motion.div onPanStart={onPanStart} />Parameter event
The originating pointer event.
Parameter info
A PanInfo object containing
x
/y
values for:-
point
: Relative to the device or page. -delta
: Distance moved since the last event. -offset
: Offset from the original pan event. -velocity
: Current velocity of the pointer.
interface PanInfo
interface PanInfo {}
Passed in to pan event handlers like
onPan
thePanInfo
object contains information about the current state of the tap gesture such as itspoint
,delta
,offset
andvelocity
.<motion.div onPan={(event, info) => {console.log(info.point.x, info.point.y)}} />Modifiers
@public
property delta
delta: Point;
Contains
x
andy
values for the distance moved since the last event.function onPan(event, info) {console.log(info.delta.x, info.delta.y)}<motion.div onPan={onPan} />Modifiers
@public
property offset
offset: Point;
Contains
x
andy
values for the distance moved from the first pan event.function onPan(event, info) {console.log(info.offset.x, info.offset.y)}<motion.div onPan={onPan} />Modifiers
@public
property point
point: Point;
Contains
x
andy
values for the current pan position relative to the device or page.function onPan(event, info) {console.log(info.point.x, info.point.y)}<motion.div onPan={onPan} />Modifiers
@public
property velocity
velocity: Point;
Contains
x
andy
values for the current velocity of the pointer, in px/ms.function onPan(event, info) {console.log(info.velocity.x, info.velocity.y)}<motion.div onPan={onPan} />Modifiers
@public
interface Repeat
interface Repeat {}
property repeat
repeat?: number;
The number of times to repeat the transition. Set to
Infinity
for perpetual repeating.Without setting
repeatType
, this will loop the animation.<motion.divanimate={{ rotate: 180 }}transition={{ repeat: Infinity, duration: 2 }}/>Modifiers
@public
property repeatDelay
repeatDelay?: number;
When repeating an animation,
repeatDelay
will set the duration of the time to wait, in seconds, between each repetition.<motion.divanimate={{ rotate: 180 }}transition={{ repeat: Infinity, repeatDelay: 1 }}/>Modifiers
@public
property repeatType
repeatType?: 'loop' | 'reverse' | 'mirror';
How to repeat the animation. This can be either:
"loop": Repeats the animation from the start
"reverse": Alternates between forward and backwards playback
"mirror": Switches
from
andto
alternately<motion.divanimate={{ rotate: 180 }}transition={{repeat: 1,repeatType: "reverse",duration: 2}}/>Modifiers
@public
interface ResolvedValues
interface ResolvedValues {}
A generic set of string/number values
index signature
[key: string]: string | number;
interface ScrollMotionValues
interface ScrollMotionValues {}
Modifiers
@public
property scrollX
scrollX: MotionValue<number>;
property scrollXProgress
scrollXProgress: MotionValue<number>;
property scrollY
scrollY: MotionValue<number>;
property scrollYProgress
scrollYProgress: MotionValue<number>;
interface SequenceLabelWithTime
interface SequenceLabelWithTime {}
interface SequenceMap
interface SequenceMap {}
index signature
[key: string]: ValueSequence;
interface SequenceOptions
interface SequenceOptions extends AnimationPlaybackOptions {}
property defaultTransition
defaultTransition?: Transition;
property delay
delay?: number;
property duration
duration?: number;
interface Spring
interface Spring extends Repeat {}
An animation that simulates spring physics for realistic motion. This is the default animation for physical values like
x
,y
,scale
androtate
.Modifiers
@public
property bounce
bounce?: number;
bounce
determines the "bounciness" of a spring animation.0
is no bounce, and1
is extremely bouncy.If
duration
is set, this defaults to0.25
.Note:
bounce
andduration
will be overridden ifstiffness
,damping
ormass
are set.<motion.divanimate={{ x: 100 }}transition={{ type: "spring", bounce: 0.25 }}/>Modifiers
@public
property damping
damping?: number;
Strength of opposing force. If set to 0, spring will oscillate indefinitely. Set to
10
by default.<motion.aanimate={{ rotate: 180 }}transition={{ type: 'spring', damping: 300 }}/>Modifiers
@public
property duration
duration?: number;
The duration of the animation, defined in seconds. Spring animations can be a maximum of 10 seconds.
If
bounce
is set, this defaults to0.8
.Note:
duration
andbounce
will be overridden ifstiffness
,damping
ormass
are set.<motion.divanimate={{ x: 100 }}transition={{ type: "spring", duration: 0.8 }}/>Modifiers
@public
property from
from?: number | string;
The value to animate from. By default, this is the initial state of the animating value.
<motion.divanimate={{ rotate: 180 }}transition={{ type: 'spring', from: 90 }}/>Modifiers
@public
property mass
mass?: number;
Mass of the moving object. Higher values will result in more lethargic movement. Set to
1
by default.<motion.feTurbulenceanimate={{ baseFrequency: 0.5 } as any}transition={{ type: "spring", mass: 0.5 }}/>Modifiers
@public
property restDelta
restDelta?: number;
End animation if distance is below this value and speed is below
restSpeed
. When animation ends, spring gets “snapped” to. Set to0.01
by default.<motion.divanimate={{ rotate: 180 }}transition={{ type: 'spring', restDelta: 0.5 }}/>Modifiers
@public
property restSpeed
restSpeed?: number;
End animation if absolute speed (in units per second) drops below this value and delta is smaller than
restDelta
. Set to0.01
by default.<motion.divanimate={{ rotate: 180 }}transition={{ type: 'spring', restSpeed: 0.5 }}/>Modifiers
@public
property stiffness
stiffness?: number;
Stiffness of the spring. Higher values will create more sudden movement. Set to
100
by default.<motion.sectionanimate={{ rotate: 180 }}transition={{ type: 'spring', stiffness: 50 }}/>Modifiers
@public
property type
type: 'spring';
Set
type
to"spring"
to animate using spring physics for natural movement. Type is set to"spring"
by default.<motion.divanimate={{ rotate: 180 }}transition={{ type: 'spring' }}/>Modifiers
@public
property velocity
velocity?: number;
The initial velocity of the spring. By default this is the current velocity of the component.
<motion.divanimate={{ rotate: 180 }}transition={{ type: 'spring', velocity: 2 }}/>Modifiers
@public
property visualDuration
visualDuration?: number;
If visualDuration is set, this will override duration.
The visual duration is a time, set in seconds, that the animation will take to visually appear to reach its target.
In other words, the bulk of the transition will occur before this time, and the "bouncy bit" will mostly happen after.
This makes it easier to edit a spring, as well as visually coordinate it with other time-based animations.
<motion.divanimate={{ x: 100 }}transition={{ type: "spring", visualDuration: 0.5 }}/>Modifiers
@public
interface SpringOptions
interface SpringOptions extends DurationSpringOptions, VelocityOptions {}
interface SVGMotionProps
interface SVGMotionProps<T> extends SVGAttributesAsMotionValues<T>, MotionProps {}
Modifiers
@public
interface TapHandlers
interface TapHandlers {}
Modifiers
@public
property globalTapTarget
globalTapTarget?: boolean;
If
true
, the tap gesture will attach its start listener to window.Note: This is not supported publically.
property whileTap
whileTap?: VariantLabels | TargetAndTransition;
Properties or variant label to animate to while the component is pressed.
<motion.div whileTap={{ scale: 0.8 }} />
method onTap
onTap: (event: MouseEvent | TouchEvent | PointerEvent, info: TapInfo) => void;
Callback when the tap gesture successfully ends on this element.
function onTap(event, info) {console.log(info.point.x, info.point.y)}<motion.div onTap={onTap} />Parameter event
The originating pointer event.
Parameter info
An TapInfo object containing
x
andy
values for thepoint
relative to the device or page.
method onTapCancel
onTapCancel: ( event: MouseEvent | TouchEvent | PointerEvent, info: TapInfo) => void;
Callback when the tap gesture ends outside this element.
function onTapCancel(event, info) {console.log(info.point.x, info.point.y)}<motion.div onTapCancel={onTapCancel} />Parameter event
The originating pointer event.
Parameter info
An TapInfo object containing
x
andy
values for thepoint
relative to the device or page.
method onTapStart
onTapStart: ( event: MouseEvent | TouchEvent | PointerEvent, info: TapInfo) => void;
Callback when the tap gesture starts on this element.
function onTapStart(event, info) {console.log(info.point.x, info.point.y)}<motion.div onTapStart={onTapStart} />Parameter event
The originating pointer event.
Parameter info
An TapInfo object containing
x
andy
values for thepoint
relative to the device or page.
interface TapInfo
interface TapInfo {}
Passed in to tap event handlers like
onTap
theTapInfo
object contains information about the tap gesture such as it‘s location.function onTap(event, info) {console.log(info.point.x, info.point.y)}<motion.div onTap={onTap} />Modifiers
@public
property point
point: Point;
Contains
x
andy
values for the tap gesture relative to the device or page.function onTapStart(event, info) {console.log(info.point.x, info.point.y)}<motion.div onTapStart={onTapStart} />Modifiers
@public
interface Tween
interface Tween extends Repeat {}
An animation that animates between two or more values over a specific duration of time. This is the default animation for non-physical values like
color
andopacity
.Modifiers
@public
property duration
duration?: number;
The duration of the tween animation. Set to
0.3
by default, 0r0.8
if animating a series of keyframes.const variants = {visible: {opacity: 1,transition: { duration: 2 }}}Modifiers
@public
property ease
ease?: Easing | Easing[];
The easing function to use. Set as one of the below.
- The name of an existing easing function.
- An array of four numbers to define a cubic bezier curve.
- An easing function, that accepts and returns a value
0-1
.If the animating value is set as an array of multiple values for a keyframes animation,
ease
can be set as an array of easing functions to set different easings between each of those values.<motion.divanimate={{ opacity: 0 }}transition={{ ease: [0.17, 0.67, 0.83, 0.67] }}/>Modifiers
@public
property easings
easings?: Easing[];
When animating keyframes,
easings
can be used to define easing functions between each keyframe. This array should be one item fewer than the number of keyframes, as these easings apply to the transitions between the keyframes.<motion.divanimate={{ backgroundColor: ["#0f0", "#00f", "#f00"] }}transition={{ easings: ["easeIn", "easeOut"] }}/>Modifiers
@public
property from
from?: number | string;
The value to animate from. By default, this is the current state of the animating value.
<motion.divanimate={{ rotate: 180 }}transition={{ from: 90, duration: 2 }}/>Modifiers
@public
property times
times?: number[];
When animating keyframes,
times
can be used to determine where in the animation each keyframe is reached. Each value intimes
is a value between0
and1
, representingduration
.There must be the same number of
times
as there are keyframes. Defaults to an array of evenly-spread durations.<motion.divanimate={{ scale: [0, 1, 0.5, 1] }}transition={{ times: [0, 0.1, 0.9, 1] }}/>Modifiers
@public
property type
type?: 'tween';
Set
type
to"tween"
to use a duration-based tween animation. If any non-orchestrationtransition
values are set without atype
property, this is used as the default animation.<motion.pathanimate={{ pathLength: 1 }}transition={{ duration: 2, type: "tween" }}/>Modifiers
@public
interface UseInViewOptions
interface UseInViewOptions extends Omit<InViewOptions, 'root' | 'amount'> {}
interface UseScrollOptions
interface UseScrollOptions extends Omit<ScrollInfoOptions, 'container' | 'target'> {}
property container
container?: RefObject$1<HTMLElement | null>;
property layoutEffect
layoutEffect?: boolean;
property target
target?: RefObject$1<HTMLElement | null>;
interface ValueAnimationOptions
interface ValueAnimationOptions<V extends string | number = number> extends ValueAnimationTransition {}
property from
from?: V;
property isGenerator
isGenerator?: boolean;
property keyframes
keyframes: V[];
property name
name?: string;
interface ValueAnimationOptionsWithRenderContext
interface ValueAnimationOptionsWithRenderContext<V extends string | number = number> extends ValueAnimationOptions<V> {}
property element
element?: VisualElement;
property KeyframeResolver
KeyframeResolver?: typeof KeyframeResolver;
property motionValue
motionValue?: MotionValue<V>;
interface ValueAnimationTransition
interface ValueAnimationTransition<V = any> extends Transition, AnimationPlaybackLifecycles<V> {}
interface VelocityOptions
interface VelocityOptions {}
interface VisualState
interface VisualState<Instance, RenderState> {}
property latestValues
latestValues: ResolvedValues;
property mount
mount?: (instance: Instance) => void;
property renderState
renderState: RenderState;
Type Aliases
type AnimationDefinition
type AnimationDefinition = VariantLabels | TargetAndTransition | TargetResolver;
type AnimationGeneratorType
type AnimationGeneratorType = | GeneratorFactory | 'decay' | 'spring' | 'keyframes' | 'tween' | 'inertia';
type AnimationOptionsWithValueOverrides
type AnimationOptionsWithValueOverrides<V = any> = StyleTransitions & SVGPathTransitions & SVGTransitions & VariableTransitions & ValueAnimationTransition<V>;
type AnimationSequence
type AnimationSequence = Segment[];
type AnimationType
type AnimationType = | 'animate' | 'whileHover' | 'whileTap' | 'whileDrag' | 'whileFocus' | 'whileInView' | 'exit';
type BezierDefinition
type BezierDefinition = readonly [number, number, number, number];
type CreateVisualElement
type CreateVisualElement<Instance> = ( Component: string | React.ComponentType<React.PropsWithChildren<unknown>>, options: VisualElementOptions<Instance>) => VisualElement<Instance>;
type Cycle
type Cycle = (i?: number) => void;
type CycleState
type CycleState<T> = [T, Cycle];
type DelayedFunction
type DelayedFunction = (overshoot: number) => void;
type Direction
type Direction = 'start' | 'end';
type DOMKeyframesDefinition
type DOMKeyframesDefinition = StyleKeyframesDefinition & SVGKeyframesDefinition & SVGPathKeyframesDefinition & VariableKeyframesDefinition;
type DOMMotionComponents
type DOMMotionComponents = HTMLMotionComponents & SVGMotionComponents;
type DOMSegment
type DOMSegment = [ElementOrSelector, DOMKeyframesDefinition];
type DOMSegmentWithTransition
type DOMSegmentWithTransition = [ ElementOrSelector, DOMKeyframesDefinition, DynamicAnimationOptions & At];
type DragElastic
type DragElastic = boolean | number | Partial<BoundingBox>;
type DynamicOption
type DynamicOption<T> = (i: number, total: number) => T;
type Easing
type Easing = EasingDefinition | EasingFunction;
The easing function to use. Set as one of:
- The name of an in-built easing function. - An array of four numbers to define a cubic bezier curve. - An easing function, that accepts and returns a progress value between
0
and1
.Modifiers
@public
type EasingDefinition
type EasingDefinition = | BezierDefinition | 'linear' | 'easeIn' | 'easeOut' | 'easeInOut' | 'circIn' | 'circOut' | 'circInOut' | 'backIn' | 'backOut' | 'backInOut' | 'anticipate';
type EasingFunction
type EasingFunction = (v: number) => number;
type EasingModifier
type EasingModifier = (easing: EasingFunction) => EasingFunction;
type FeatureDefinition
type FeatureDefinition = { isEnabled: HydratedFeatureDefinition['isEnabled']; Feature?: HydratedFeatureDefinition['Feature']; ProjectionNode?: HydratedFeatureDefinition['ProjectionNode']; MeasureLayout?: HydratedFeatureDefinition['MeasureLayout'];};
type FeatureDefinitions
type FeatureDefinitions = { [K in keyof HydratedFeatureDefinitions]: FeatureDefinition;};
type FeaturePackage
type FeaturePackage = { Feature?: HydratedFeatureDefinition['Feature']; ProjectionNode?: HydratedFeatureDefinition['ProjectionNode']; MeasureLayout?: HydratedFeatureDefinition['MeasureLayout'];};
type FeaturePackages
type FeaturePackages = { [K in keyof HydratedFeatureDefinitions]: FeaturePackage;};
type ForwardRefComponent
type ForwardRefComponent<T, P> = { readonly $$typeof: symbol;} & ((props: PropsWithoutRef<P> & RefAttributes<T>) => JSX.Element);
Modifiers
@public
type GeneratorFactory
type GeneratorFactory = ( options: ValueAnimationOptions<any>) => KeyframeGenerator<any>;
type HTMLMotionProps
type HTMLMotionProps<Tag extends keyof HTMLElements> = AttributesWithoutMotionProps< JSX.IntrinsicElements[Tag]> & MotionProps;
Modifiers
@public
type HydratedFeatureDefinition
type HydratedFeatureDefinition = { isEnabled: (props: MotionProps) => boolean; Feature: FeatureClass<unknown>; ProjectionNode?: any; MeasureLayout?: typeof MeasureLayout;};
type KeyframesTarget
type KeyframesTarget = | ResolvedKeyframesTarget | GenericKeyframesTarget<CustomValueType>;
Modifiers
@public
type LazyFeatureBundle
type LazyFeatureBundle$1 = () => Promise<FeatureBundle>;
type MixerFactory
type MixerFactory<T> = (from: T, to: T) => Mix<T>;
type MotionStyle
type MotionStyle = MotionCSS & MotionTransform & MakeMotion<SVGPathProperties> & MakeCustomValueType<CustomStyles>;
Modifiers
@public
type MotionTransform
type MotionTransform = MakeMotion<TransformProperties>;
Modifiers
@public
type MotionValueSegment
type MotionValueSegment = [ MotionValue, UnresolvedValueKeyframe | UnresolvedValueKeyframe[]];
type MotionValueSegmentWithTransition
type MotionValueSegmentWithTransition = [ MotionValue, UnresolvedValueKeyframe | UnresolvedValueKeyframe[], Transition & At];
type ObjectSegment
type ObjectSegment<O extends {} = {}> = [O, ObjectTarget<O>];
type ObjectSegmentWithTransition
type ObjectSegmentWithTransition<O extends {} = {}> = [ O, ObjectTarget<O>, DynamicAnimationOptions & At];
type ObjectTarget
type ObjectTarget<O> = { [K in keyof O]?: O[K] | GenericKeyframesTarget<O[K]>;};
type PassiveEffect
type PassiveEffect<T> = (v: T, safeSetter: (v: T) => void) => void;
Modifiers
@public
type RenderComponent
type RenderComponent<Instance, RenderState> = ( Component: string | React$1.ComponentType<React$1.PropsWithChildren<unknown>>, props: MotionProps, ref: React$1.Ref<Instance>, visualState: VisualState<Instance, RenderState>, isStatic: boolean, visualElement?: VisualElement<Instance>) => any;
type RepeatType
type RepeatType = 'loop' | 'reverse' | 'mirror';
type ResolvedAnimationDefinition
type ResolvedAnimationDefinition = { keyframes: { [key: string]: UnresolvedValueKeyframe[]; }; transition: { [key: string]: Transition; };};
type ResolvedAnimationDefinitions
type ResolvedAnimationDefinitions = Map< Element | MotionValue, ResolvedAnimationDefinition>;
type ResolvedKeyframesTarget
type ResolvedKeyframesTarget = | GenericKeyframesTarget<number> | GenericKeyframesTarget<string>;
Modifiers
@public
type ResolvedSingleTarget
type ResolvedSingleTarget = string | number;
Modifiers
@public
type ResolvedValueTarget
type ResolvedValueTarget = ResolvedSingleTarget | ResolvedKeyframesTarget;
Modifiers
@public
type ResolveKeyframes
type ResolveKeyframes<V extends string | number> = ( keyframes: V[], onComplete: OnKeyframesResolved<V>, name?: string, motionValue?: any) => KeyframeResolver<V>;
type ScrapeMotionValuesFromProps
type ScrapeMotionValuesFromProps = ( props: MotionProps, prevProps: MotionProps, visualElement?: VisualElement) => { [key: string]: MotionValue | string | number;};
type Segment
type Segment = | ObjectSegment | ObjectSegmentWithTransition | SequenceLabel | SequenceLabelWithTime | MotionValueSegment | MotionValueSegmentWithTransition | DOMSegment | DOMSegmentWithTransition;
type SequenceLabel
type SequenceLabel = string;
type SequenceTime
type SequenceTime = number | '<' | `+${number}` | `-${number}` | `${string}`;
type SingleTarget
type SingleTarget = ResolvedSingleTarget | CustomValueType;
Modifiers
@public
type StyleKeyframesDefinition
type StyleKeyframesDefinition = { [K in keyof CSSStyleDeclarationWithTransform]?: ValueKeyframesDefinition;};
type StyleTransitions
type StyleTransitions = { [K in keyof CSSStyleDeclarationWithTransform]?: Transition;};
type Subscriber
type Subscriber<T> = (v: T) => void;
Modifiers
@public
type SVGAttributesAsMotionValues
type SVGAttributesAsMotionValues<T> = MakeMotion<SVGAttributesWithoutMotionProps<T>>;
Blanket-accept any SVG attribute as a
MotionValue
Modifiers
@public
type SVGKeyframesDefinition
type SVGKeyframesDefinition = { [K in keyof SVGAttributes]?: ValueKeyframesDefinition;};
type SVGPathKeyframesDefinition
type SVGPathKeyframesDefinition = { [K in keyof SVGPathProperties]?: ValueKeyframesDefinition;};
type SVGPathTransitions
type SVGPathTransitions = { [K in keyof SVGPathProperties]: Transition;};
type SVGTransitions
type SVGTransitions = { [K in keyof SVGAttributes]: Transition;};
type SwitchLayoutGroupContext
type SwitchLayoutGroupContext = SwitchLayoutGroup & InitialPromotionConfig;
type Target
type Target = MakeCustomValueType<TargetProperties>;
Modifiers
@public
type TargetAndTransition
type TargetAndTransition = TargetWithKeyframes & { transition?: Transition$1; transitionEnd?: Target;};
An object that specifies values to animate to. Each value may be set either as a single value, or an array of values.
It may also option contain these properties:
-
transition
: Specifies transitions for all or individual values. -transitionEnd
: Specifies values to set when the animation finishes.const target = {x: "0%",opacity: 0,transition: { duration: 1 },transitionEnd: { display: "none" }}Modifiers
@public
type TransformPoint
type TransformPoint = (point: Point) => Point;
type Transition
type Transition$1 = | (Orchestration & Repeat & TransitionDefinition) | (Orchestration & Repeat & TransitionMap);
Transition props
Modifiers
@public
type UnresolvedValueKeyframe
type UnresolvedValueKeyframe = ValueKeyframe | null;
type ValueKeyframe
type ValueKeyframe = string | number;
type ValueKeyframesDefinition
type ValueKeyframesDefinition = | ValueKeyframe | ValueKeyframe[] | UnresolvedValueKeyframe[];
type ValueSequence
type ValueSequence = AbsoluteKeyframe[];
type ValueTarget
type ValueTarget = SingleTarget | KeyframesTarget;
Modifiers
@public
type ValueType
type ValueType = { test: (v: any) => boolean; parse: (v: any) => any; transform?: Transformer; createTransformer?: (template: string) => Transformer; default?: any; getAnimatableNone?: (v: any) => any;};
type VariableKeyframesDefinition
type VariableKeyframesDefinition = { [key: `--${string}`]: ValueKeyframesDefinition;};
type VariableTransitions
type VariableTransitions = { [key: `--${string}`]: Transition;};
type Variant
type Variant = TargetAndTransition | TargetResolver;
Modifiers
@public
type VariantLabels
type VariantLabels = string | string[];
Either a string, or array of strings, that reference variants defined via the
variants
prop.Modifiers
@public
type Variants
type Variants = { [key: string]: Variant;};
Modifiers
@public
Namespaces
namespace global
namespace global {}
interface Window
interface Window {}
property ScrollTimeline
ScrollTimeline: ScrollTimeline;
interface Window
interface Window {}
property MotionCancelOptimisedAnimation
MotionCancelOptimisedAnimation?: ( elementId?: string, valueName?: string, frame?: Batcher, canResume?: boolean) => void;
property MotionCheckAppearSync
MotionCheckAppearSync?: ( visualElement: WithAppearProps, valueName: string, value: MotionValue) => VoidFunction | void;
property MotionHandoffAnimation
MotionHandoffAnimation?: HandoffFunction;
property MotionHandoffIsComplete
MotionHandoffIsComplete?: (elementId: string) => boolean;
property MotionHandoffMarkAsComplete
MotionHandoffMarkAsComplete?: (elementId: string) => void;
property MotionHasOptimisedAnimation
MotionHasOptimisedAnimation?: ( elementId?: string, valueName?: string) => boolean;
property MotionIsMounted
MotionIsMounted?: boolean;
Package Files (1)
Dependencies (3)
Dev Dependencies (2)
Peer Dependencies (3)
Badge
To add a badge like this oneto your package's README, use the codes available below.
You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/framer-motion
.
- Markdown[![jsDocs.io](https://img.shields.io/badge/jsDocs.io-reference-blue)](https://www.jsdocs.io/package/framer-motion)
- HTML<a href="https://www.jsdocs.io/package/framer-motion"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>
- Updated .
Package analyzed in 13026 ms. - Missing or incorrect documentation? Open an issue for this package.