# Inertia — full API reference > This file holds every documentation page, in source order. scripts/build-llms.mjs builds it from docs/docs/*.md. Don't edit it by hand. > Source: https://github.com/rootnative/inertia > Site: https://rootnative.github.io/inertia/ --- Inertia (`@rootnative/inertia`) is a thin wrapper around `react-native-reanimated`. You write an animation as props on a component: no shared values, no worklets, no `useAnimatedStyle` boilerplate. The vocabulary takes ideas from **Framer Motion** (web) and **react-spring** (cross-platform). Inertia supports iOS, Android, and web (react-native-web). macOS, Windows, and Electron are not tested. See [Platforms](./installation#platforms). > **Status:** `0.0.30`. The example app covers the full surface: primitives, per-property transitions, sequences, variants, gestures, ``, decay, ``, layout, shared elements, and the value-layer hooks. The [changelog](https://github.com/rootnative/inertia/blob/main/packages/core/CHANGELOG.md) names each breaking change. ## What you get - **DX-first.** Animations are props on a component, not shared values, worklets, and `useAnimatedStyle` boilerplate. - **Per-primitive style inference.** `Motion.View` accepts `ViewStyle` keys, `Motion.Text` accepts `TextStyle` keys, and `Motion.Image` accepts `ImageStyle` keys. There is no shared union fallback, so a wrong prop is a type error. - **react-spring vocabulary.** A spring config uses `tension`, `friction`, `mass`, and `velocity`. Reanimated's raw `stiffness` and `damping` never appear in the public surface. - **One `gesture` prop on every primitive.** The sub-states are `pressed`, `focused`, `focusVisible` (W3C `:focus-visible`), and `hovered` (web). There is no `whileTap` or `whilePress` family, and no separate "pressable" variant. - **Per-primitive tree-shaking.** Subpath imports (`@rootnative/inertia/view`, `/text`, `/image`, `/pressable`, `/scroll-view`) let an app that animates one element skip the rest of the library. - **Stable worklets.** The factory hashes the resolved `animate` and `transition` objects and memoizes the generated worklet and `useAnimatedStyle`. A re-render with the same values makes no new UI-thread closure. ## Install Pick your package manager. Yarn is the default, and your choice applies to every install snippet in the docs. ```bash yarn add @rootnative/inertia react-native-reanimated react-native-worklets ``` Then enable the `react-native-worklets/plugin` Babel plugin as the Reanimated [install guide](https://docs.swmansion.com/react-native-reanimated/docs/fundamentals/installation) shows. [Installation](./installation) has a full `babel.config.js`. ## A first animation ```tsx import { Motion } from '@rootnative/inertia' export function FadeIn() { return ( ) } ``` To ship only one primitive, import it from its subpath: ```ts import { MotionView } from '@rootnative/inertia/view' ``` ## Runnable example The full example app runs below. It holds every primitive and every gesture, with the same code that ships under `example/` in the repo. Tap a screen to try it: Each docs page links to the matching screen of this same app, so you can try the API as you read. ## Where to next - [Installation](./installation): install the peers and the Reanimated Babel plugin. - [Primitives](./primitives/index.md): `Motion.View`, `Motion.Text`, `Motion.Image`, `Motion.Pressable`, `Motion.ScrollView`, and `Motion.FlatList`. - [Transitions](./transitions): `spring` (default), `timing`, `decay`, and `no-animation`. - [Sequences & repeat](./sequences): keyframe arrays and the one `repeat` shape. - [Variants](./variants): named animation states and the `useVariants` controller. - [Gestures](./gestures): the `pressed`, `focused`, `focusVisible`, and `hovered` sub-states. - [Gestures adapter](./gestures-adapter): drag, pan, and swipe with `react-native-gesture-handler` (optional package). - [Gradients](./gradients): the animatable `MotionLinearGradient` on `expo-linear-gradient` (optional package). - [SVG](./svg): the animatable `MotionPath` on `react-native-svg` (optional package). - [Presence](./presence): mount and unmount transitions. - [Layout](./layout): animate a change of position or size. - [MotionConfig](./motion-config): the reduce-motion gate and named transitions. - [Hooks](./api/hooks) and [createMotionComponent](./api/create-motion-component): the escape hatches. - [AI agents & llms.txt](./ai): machine-readable API references for coding agents, hosted here and shipped in every npm package. --- # Installation Inertia is a thin wrapper around `react-native-reanimated`. Install Reanimated first: Inertia is a peer of Reanimated, not a replacement. ## Prerequisites - Expo SDK `58` (React Native `0.88.x`, React `19.3.0`), or a bare React Native app with no Expo on the same versions - `react-native-reanimated` `>=4.7.0 <4.8.0` - `react-native-worklets` `>=0.13.0 <0.14.0`, the worklet runtime of Reanimated 4. It's a **peer** of both Reanimated and Inertia, so Yarn and pnpm won't install it for you. Each release of `@rootnative/inertia` is bundled in an Expo app and in a bare React Native app with no Expo before it's published. Of the adapters, only `@rootnative/inertia-gradients` needs Expo: it runs on the Expo modules runtime. See [Gradients](./gradients). Each release line supports one Expo SDK band. Install the line that matches the SDK of the app. | Expo SDK | `@rootnative/inertia` and the adapters | | -------- | --------------------------------------------------------------- | | 58 | `0.0.20` and later | | 57 | `0.0.11` to `0.0.19` (`npm install @rootnative/inertia@0.0.19`) | | 54 | `0.0.10` and earlier, with a lockfile that already resolved | On SDK 57 with `0.0.19`, install Reanimated **4.5.3 or later** in a development build or a store build. Reanimated 4.5.0 to 4.5.2 can show a view at its `initial` value after its animation ends. The cause: native keeps a settled value for 2 s only, and React holds the first-render value. When the JS thread doesn't read the settled value in that window (a stall of more than 1 s, a paused app, a native dialog), the next React commit writes the `initial` value back. An entrance from `opacity: 0` then goes blank with no error. Reanimated 4.5.3 keeps the value until React has it ([software-mansion/react-native-reanimated#9987](https://github.com/software-mansion/react-native-reanimated/pull/9987)). The fix is native, so it needs a new build, not an over-the-air update. Expo SDK 57 pins `4.5.1`: add `react-native-reanimated` to `expo.install.exclude` in `package.json`, or `expo install --check` moves it back. Expo Go 57 runs 4.5.1 and can't change, so a project in Expo Go keeps the defect. The SDK 58 band starts at Reanimated 4.7, which has the fix. Inertia targets **one SDK band, not a floor**, so `SDK 58+` is not correct. The peer ranges stop below React Native 0.89 and below Reanimated 4.8, which the next SDK will carry. The upper bounds are deliberate. Reanimated and `react-native-worklets` are version-locked to each other, and each pair works with one React Native band. Reanimated 4.7 needs worklets `0.13.x` and React Native 0.86 to 0.88. A wider range would let a package manager pair a new Reanimated with an old worklets, and that pair can't install at all. A second SDK needs a second release line, not a wider range. ## Platforms | Platform | Status | | ------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- | | iOS | Supported | | Android | Supported | | Web (react-native-web `0.21`, through Expo) | Supported. The example app and the docs demo run on web. Tests ran in Chromium only. Safari and Firefox are not tested. | | macOS (react-native-macos) | Not tested | | Windows (react-native-windows) | Not tested | | Electron | Not tested. Expo does not supply an Electron target. | Inertia uses the same API on every supported platform. For web, add the web dependencies to an Expo app: ```bash npx expo install react-dom react-native-web ``` Some behavior is different on web: - `gesture.hovered` works on web only. On iOS and Android it does nothing. See [Gestures](./gestures). - `layoutId` measures the DOM rect with `getBoundingClientRect()` on web. See [Layout](./layout). - A static web export writes each element at its `initial` values. Without the entrance guard, the page stays blank when the JavaScript bundle doesn't run. See [Static export](./static-export). The adapter packages use the web support of their peer dependency: - `@rootnative/inertia-gestures` works on web through the web support of `react-native-gesture-handler`. - `@rootnative/inertia-svg` works on web through the web support of `react-native-svg`. - `@rootnative/inertia-gradients` works on web through the web component of `expo-linear-gradient`. On web, Reanimated can log a console error on each frame for this component. The gradient renders and animates correctly. ## Which package has what Read this before you install. The core package doesn't contain the gesture hooks, the gradient primitive, or the SVG primitives. Each one is a separate install. A swipe deck is a common reason to use this library, and `useSwipe` is **not** in the core package. | You want | Package | Install | | ------------------------------------------------------------------------- | ------------------------------- | -------------------------------- | | `Motion.*` primitives, `Presence`, `MotionConfig`, every value-layer hook | `@rootnative/inertia` | core, always required | | `useDrag`, `useSwipe`, `usePan` | `@rootnative/inertia-gestures` | + `react-native-gesture-handler` | | Animatable linear gradients | `@rootnative/inertia-gradients` | + `expo-linear-gradient` | | Animatable SVG paths and shapes | `@rootnative/inertia-svg` | + `react-native-svg` | `useTouchDrag` is the exception. It's a drag hook in **core**, under the `@rootnative/inertia/touch` subpath, because PanResponder is part of React Native and needs no extra peer dependency. Use it when you want drag without `react-native-gesture-handler`, or when the drag needs keyboard accessibility. ### Versions All four packages ship in **lockstep**: the same version number, released together. Install the same version of every `@rootnative/inertia*` package you use. Each adapter requires a core version at or above its own. Other packages in the `@rootnative` scope are different libraries with their own versions. A different version there isn't a mismatch. ## Install Yarn is the default. Switch tabs for npm, pnpm, or Bun. Your choice applies to every install snippet in the docs. ```bash yarn add @rootnative/inertia react-native-reanimated react-native-worklets ``` Then enable the worklets Babel plugin as the Reanimated [install guide](https://docs.swmansion.com/react-native-reanimated/docs/fundamentals/installation) shows. The plugin transforms each `'worklet'` function into UI-thread code. Without the plugin, every animation crashes at runtime. A typical `babel.config.js` for a managed Expo app: ```js module.exports = function (api) { api.cache(true) return { presets: ['babel-preset-expo'], plugins: ['react-native-worklets/plugin'], } } ``` The worklets plugin must be **last** in the plugins array. `react-native-reanimated/plugin` still works in Reanimated 4: it's a one-line shim that forwards to `react-native-worklets/plugin`. The worklets name is the canonical one, and Inertia's own install check tells you to add that name. ### The plugin must run on `node_modules` too `@rootnative/inertia`, `react-native-reanimated`, and `react-native-worklets` all ship their `'worklet'` directives untransformed. The plugin in your build turns them into UI-thread code. Metro runs Babel on `node_modules`, so an Expo or bare React Native app needs only the config above. A web bundler without Metro (Vite, webpack, Electron, Tauri) skips `node_modules` by default. The build then succeeds, and no animation plays: every animated style stays at its first frame, and a production build shows no error. In that case Inertia logs one `console.error` at the first `Motion` render, in production too. Add the three packages to the include list of the plugin. A Vite example with `@rolldown/plugin-babel`: ```ts babel({ include: [ /src\/.*\.tsx?$/, /node_modules\/(@rootnative|react-native-reanimated|react-native-worklets)\/.*\.m?js$/, ], plugins: ['react-native-worklets/plugin'], }) ``` The equivalent for `babel-loader` in webpack is an `include` array with the same paths. ## First animation ```tsx import { Motion } from '@rootnative/inertia' export function FadeIn() { return ( ) } ``` ### Try it live The example app runs in the iframe below. Tap a screen to try the same primitives that you ship in your app. ## Subpath imports Each primitive has its own import path, so an app that animates one element doesn't pull in the rest: ```ts import { MotionView } from '@rootnative/inertia/view' import { MotionText } from '@rootnative/inertia/text' import { MotionImage } from '@rootnative/inertia/image' import { MotionPressable } from '@rootnative/inertia/pressable' import { MotionScrollView } from '@rootnative/inertia/scroll-view' ``` `@rootnative/inertia` is `sideEffects: false`, so a bundler with tree-shaking (Metro 0.79+, Webpack, Rollup) drops the primitives that you don't import. The named imports above tree-shake to within about 0.1 kB of the subpath imports. CI checks this for each primitive. One caveat: the `Motion` namespace object can't tree-shake. `import { Motion } from '@rootnative/inertia'` followed by `Motion.View` keeps the whole namespace in the bundle, because a bundler can't remove a property access on a literal object. Use the namespace for comfort. Use `import { MotionView } from '@rootnative/inertia'` (or the subpath) when bundle size matters. ## Optional adapter packages Three sibling packages extend Inertia with features that need extra peer dependencies. The core library doesn't depend on any of them. Install only what you need. ### Gestures (`@rootnative/inertia-gestures`) Drag, pan, and swipe hooks on [`react-native-gesture-handler`](https://docs.swmansion.com/react-native-gesture-handler). Compose them with any `Motion.*` primitive through ``. ```bash yarn add @rootnative/inertia-gestures react-native-gesture-handler ``` Then follow the [`react-native-gesture-handler` install guide](https://docs.swmansion.com/react-native-gesture-handler/docs/installation). It needs `` near the root of your app. See [Gestures adapter](./gestures-adapter) for the hooks. ### Gradients (`@rootnative/inertia-gradients`) `MotionLinearGradient` wraps [`expo-linear-gradient`](https://docs.expo.dev/versions/latest/sdk/linear-gradient/) with animatable `colors`, `start`, `end`, and `locations`. It works in bare React Native and in Expo, but `expo-linear-gradient` is an Expo Module. A bare project needs the Expo modules runtime. See [Installing Expo modules](https://docs.expo.dev/bare/installing-expo-modules/). ```bash yarn add @rootnative/inertia-gradients expo-linear-gradient ``` See [Gradients](./gradients) for the primitive. ### SVG (`@rootnative/inertia-svg`) `MotionPath` wraps the `` of [`react-native-svg`](https://github.com/software-mansion/react-native-svg) with animatable `d` (path morphing between paths with the same structure), `fill`, `stroke`, `strokeWidth`, opacities, and `strokeDashoffset`. It works in bare React Native and in Expo. ```bash yarn add @rootnative/inertia-svg react-native-svg ``` See [SVG](./svg) for the primitive. ## Reduced motion Inertia follows the reduce-motion accessibility setting of the OS by default. You need no extra setup. To override the default for the whole app or a subtree, see [MotionConfig](./motion-config). --- # Primitives Every animatable surface is a `Motion.*` component. Each one is an animatable mirror of a React Native primitive. The props stay the same, except `style`, plus the Motion props: `initial`, `animate`, `exit`, `variants`, `controller`, `gesture`, `transition`, `onAnimationEnd`, `layout`, and `layoutId`. | Component | Wraps RN's | Style type | | ------------------------------------ | ------------ | ------------ | | [`Motion.View`](./view) | `View` | `ViewStyle` | | [`Motion.Text`](./text) | `Text` | `TextStyle` | | [`Motion.Image`](./image) | `Image` | `ImageStyle` | | [`Motion.Pressable`](./pressable) | `Pressable` | `ViewStyle` | | [`Motion.ScrollView`](./scroll-view) | `ScrollView` | `ViewStyle` | | [`Motion.FlatList`](./flat-list) | `FlatList` | `ViewStyle` | ## Per-primitive style inference `animate`, `initial`, `exit`, and the `gesture` sub-states take the type of the `style` prop of the component. There is no shared `ViewStyle & TextStyle & ImageStyle` fallback. So `tintColor` autocompletes on `Motion.Image`, and `Motion.View` rejects it at compile time. ```tsx // ✅ // ❌ TS error ``` ## Custom primitives Wrap any component with `createMotionComponent(C)` to get the same prop surface, inferred from the style prop of `C`. See [createMotionComponent](../api/create-motion-component). ## Plain host (zero-cost pass-through) A `Motion.*` primitive with **none** of the animation props (`initial`, `animate`, `exit`, `transition`, `variants`, `controller`, `gesture`, `layout`, `layoutId`, `onAnimationEnd`) is a zero-cost pass-through over `Animated.createAnimatedComponent(Component)`. It allocates no shared values, mounts no `useAnimatedStyle` worklet, holds no gesture state, and does no animation work per render. It forwards `style`, `ref`, and every other prop straight to the host. A guard test pins this: a `Motion.View` with no props calls neither `useSharedValue` nor `useAnimatedStyle`. So you never need `Animated.View` from the [`/reanimated` interop subpath](../api/reanimated-interop) only to render an animated-style **fragment** from a value-layer hook. Use the primitive directly: ```tsx import { Motion, useColorTransition } from '@rootnative/inertia' function Fill({ progress }) { const fill = useColorTransition(progress, ['#ffffff', '#4f46e5']) // Prop-less Motion.View — a plain animated host for the fragment. No // Reanimated import needed. return } ``` When you add an animation prop, the same instance opts into the full animated body. It remounts across that boundary, so give an element that switches between plain and animated a stable `key` if the remount matters. There is one host concept, and no separate "plain" alias to pick. ## Animatable properties Inertia supports the properties below on every primitive that accepts them. `animate` is typed per primitive **and** narrowed to this set. A style key that Inertia doesn't drive is a compile error, not a silent no-op. So a typo or an unsupported property fails the build instead of doing nothing at runtime. **Numeric:** `opacity`, `translateX`, `translateY`, `scale`, `scaleX`, `scaleY`, `rotate`, `rotateX`, `rotateY`, `width`, `height`, `borderRadius`, `shadowOpacity`, `shadowRadius`, `elevation`. A rotation value is degrees as a number. The runtime adds `'deg'` before it passes the value to Reanimated. **Layout numerics** (since `0.0.5`): | Group | Keys | | ----------------- | --------------------------------------------------------------------------------------------------------------- | | Per-corner radius | `borderTopLeftRadius`, `borderTopRightRadius`, `borderBottomLeftRadius`, `borderBottomRightRadius` | | Border width | `borderWidth`, `borderTopWidth`, `borderRightWidth`, `borderBottomWidth`, `borderLeftWidth` | | Absolute inset | `top`, `right`, `bottom`, `left` | | Padding | `padding`, `paddingTop`, `paddingRight`, `paddingBottom`, `paddingLeft`, `paddingHorizontal`, `paddingVertical` | | Margin | `margin`, `marginTop`, `marginRight`, `marginBottom`, `marginLeft`, `marginHorizontal`, `marginVertical` | | Flex sizing | `flex`, `flexGrow`, `flexShrink` | | Gap | `gap`, `rowGap`, `columnGap` | | Stacking | `zIndex` | | Text metrics | `fontSize`, `letterSpacing`, `lineHeight` — `Motion.Text` only, since they live on `TextStyle` | These keys animate the box itself, not a transform, so they trigger layout on each frame. Prefer `scale` and `translateX` for pure motion. They run on the compositor and don't reflow. Use the layout keys when the effect _is_ a layout change: a drawer that slides with `left`, a card that squares one corner as it expands, a pane that resizes with `flex`. **Not animatable, on purpose:** an enum key (`position`, `overflow`, `alignItems`, `flexDirection`, `display`) has nothing to interpolate between. `minWidth`, `maxWidth`, `minHeight`, `maxHeight`, and `aspectRatio` are excluded for a subtler reason. Their unset state isn't a number. So there is no value for the key to rest at when only a `gesture` sub-state or an inactive variant declares it, without a layout change the moment it activates. Animate `width` or `height` instead, or use the [value-layer hooks](../api/hooks). **Shadow offset:** `shadowOffset` accepts the nested `{ width, height }` object, in the single-value form only. See [Motion.View](./view) for the contract. **Box shadow:** `boxShadow` animates the cross-platform CSS shadow form. See [Motion.View](./view#boxshadow) for the layer-count rules and the `inset` constraint. Don't animate it next to the native `shadow*` keys on the same element. That applies two shadow systems at once, and Inertia warns in dev when it sees both. **Color:** `backgroundColor`, `borderColor`, `color`, `shadowColor`, `tintColor` (Image only). Any color string that Reanimated knows works: hex (`'#4f46e5'`, `'#fff'`), `rgb()` and `rgba()`, `hsl()` and `hsla()`, and named colors, including `'transparent'`. Inertia forwards the target straight through `withSpring` or `withTiming`. The value setter of Reanimated packs the string to RGBA and interpolates on the UI thread. ```tsx ``` When you omit `initial`, a color slot seeds with `'transparent'`. That is fine for a fade-in. When you animate between two opaque values, pass an explicit `initial` color, so the first frame doesn't flash through transparent. **Optional adapter primitives:** gradient interpolation ships in [`@rootnative/inertia-gradients`](../gradients) (`MotionLinearGradient`), and SVG path morphing ships in [`@rootnative/inertia-svg`](../svg) (`MotionPath`). Both take the same `initial`, `animate`, and `transition` shape. **Layout transitions:** the [`layout` prop](../layout) animates a change of position or size that comes from outside the `animate` flow, such as a reorder of siblings or a change of dimensions. **Shared element transitions:** the [`layoutId` prop](../layout#shared-element-transitions-layoutid) runs a FLIP between two `Motion.*` primitives that mount with the same id, across a mount or a screen, with no animation config beyond the shared id. --- # Motion.View Animatable `View`. It's the default primitive. Use it for boxes, surfaces, and anything that isn't text, an image, a scroll container, or a pressable. ```tsx import { Motion } from '@rootnative/inertia' export function Card() { return ( ) } ``` ## Tree-shaken import ```ts import { MotionView } from '@rootnative/inertia/view' ``` ## Animatable keys `opacity`, `translateX`, `translateY`, `scale`, `scaleX`, `scaleY`, `rotate`, `rotateX`, `rotateY`, `width`, `height`, `borderRadius`, `shadowOpacity`, `shadowRadius`, `elevation`, `backgroundColor`, `borderColor`, `shadowColor`, `shadowOffset`, `boxShadow`. Since `0.0.5`, also the layout numerics: the per-corner radii (`borderTopLeftRadius` and its siblings), the border widths (`borderWidth`, `borderTopWidth`, …), the absolute insets (`top`, `right`, `bottom`, `left`), padding and margin (including the `*Horizontal` and `*Vertical` shorthands), `flex`, `flexGrow`, `flexShrink`, `gap`, `rowGap`, `columnGap`, and `zIndex`. See [Animatable properties](.#animatable-properties) for the full table, the layout-cost caveat, and the list of excluded keys. Any key outside that set is a **compile error** on `animate`, not a silent no-op. `animate={{ alignItems: 'center' }}` fails the type check instead of rendering nothing. ## Animating layout vs. transforms `width`, `height`, `padding`, `flex`, and the inset keys all drive real layout, so each frame reflows the subtree. That is the correct tool when the layout changes, but it costs measurably more than the compositor-only transform path: ```tsx // Prefer this for pure motion — no reflow. // Use this when the box itself must change (siblings should reflow around it). ``` A `width` or `height` animation on a container that isn't `flex: 1` can jitter on Fabric. The same caveat applies to the layout keys above. For a size change that only has to _look_ right, `scaleX` and `scaleY` are smoother. ## Shadow animation The shadow keys use the same animatable pipeline as the other numeric and color props. `shadowOpacity`, `shadowRadius`, and `elevation` are numbers. `shadowColor` is a color. `shadowOffset` is the one nested-object style on the surface. Internally, the worklet splits it into two synthetic axis shared values and joins them into one `{ width, height }` prop on each frame. ```tsx // MD3 elevation cascade — flat numerics + the nested shadowOffset ``` `shadowOffset` supports the **single-value form only**: `{ width: number, height: number }`. A sequence inside the nested object (`{ width: [0, 100, 0], height: 0 }`) and an array of keyframes on the whole object are out of scope. Use the value-layer hooks (`useMotionValue` and `useAnimatedStyle`) when you need them. A transition per axis is also out of scope. The top-level `transition.shadowOffset` applies to both axes. ## `boxShadow` `boxShadow` animates the cross-platform CSS shadow form. It accepts a CSS string, the form in which a design system stores its elevation tokens, or the array of layers of React Native: ```tsx ``` ```tsx // Equivalent structured form — lengths may be numbers or px strings. ``` **The two ends can have a different number of layers.** Inertia pads the shorter side with a transparent zero layer, the same as a CSS transition. So a one-layer shadow that animates to a two-layer shadow fades the extra layer in and doesn't pop it. Every length and color interpolates per layer. **`inset` doesn't interpolate.** It travels as a static flag per layer, because there is no meaningful midpoint between an inner and an outer shadow. Both ends can use `inset`. A layer that is `inset` on one side and not on the other throws. Pad with a transparent layer if the counts must line up differently. **Two constraints to know:** - **No sequence on this key.** `boxShadow: [a, b]` means one two-layer shadow, not a two-step keyframe sequence. The array slot belongs to the layers, and nothing tells the two shapes apart structurally. This is the same single-value contract as `shadowOffset`. Per-property transitions still work. - **Not available in a `gesture` sub-state.** A layer stack in the priority cascade would mean interpolation per layer on the UI thread for every primitive. Drive it from `animate` instead, optionally through a variant keyed on the same state, or interpolate it yourself with [`useShadow`](../api/hooks#useshadow-from-to-progress-). Inertia warns in dev when it finds `boxShadow` inside a `gesture` sub-state. Only px and unitless lengths are supported. `em`, `%`, and `rem` depend on a font or viewport context that a style value can't resolve. Inertia rejects them instead of an animation from `NaN`. Don't animate `boxShadow` and the native `shadow*` keys on the same element. That applies two shadow systems at once, and the one that the view resolves last wins. Inertia warns in dev when both appear in the animated key set of one instance. ## Notes - Inertia composes `transform` for you. Transform keys in one `animate` object (for example `translateX` and `scale`) emit one `transform` array. You don't write `transform: [...]` yourself. - `rotate`, `rotateX`, and `rotateY` are numbers, in degrees. The factory wraps each one as `{ rotate: '${value}deg' }` (and so on) for Reanimated. Use `rotateX` or `rotateY` together with a `perspective` style entry, so the 3D effect renders. - A `width` or `height` interpolation can jitter on Fabric on a container that isn't `flex: 1`. Prefer `scaleX` and `scaleY` for a resize animation where the layout impact is acceptable. - Shadow rendering is platform-specific. iOS uses `shadowColor`, `shadowOpacity`, `shadowOffset`, and `shadowRadius`. Android uses `elevation`, which derives its own shadow. Animate both sets together when you need a cross-platform cascade. --- # Motion.Text Animatable `Text`. `animate`, `initial`, `exit`, and `gesture` take the `TextStyle` type. ```tsx import { Motion } from '@rootnative/inertia' export function Heading({ visible }: { visible: boolean }) { return ( Hello ) } ``` ## Tree-shaken import ```ts import { MotionText } from '@rootnative/inertia/text' ``` ## Animatable keys `opacity`, `translateX`, `translateY`, `scale`, `scaleX`, `scaleY`, `rotate`, `rotateX`, `rotateY`, `width`, `height`, `borderRadius`, `color`, `backgroundColor`, plus the layout numerics listed in [Animatable properties](.#animatable-properties). **Text metrics.** `fontSize`, `letterSpacing`, and `lineHeight` animate since `0.0.5`. Before that, they passed the type check but did nothing, and the docs recommended a hand-written `useAnimatedStyle`. You don't need that workaround anymore. They exist on `TextStyle` only, so `Motion.View` and `Motion.Image` reject them at compile time. ```tsx Scaling headline ``` Each of these keys measures the text again on every frame, which costs more than the transform path. When the text only has to _look_ bigger, and you don't want a reflow, animate `scale` instead. It composites with no new measurement. Use `fontSize` when the content around the text must reflow around the new size. ```tsx Tap me ``` --- # Motion.Image Animatable `Image`. `animate`, `initial`, `exit`, and `gesture` take the `ImageStyle` type, so `tintColor` autocompletes here, and the other primitives reject it. ```tsx import { Motion } from '@rootnative/inertia' export function Avatar({ source }: { source: { uri: string } }) { return ( ) } ``` ## Tree-shaken import ```ts import { MotionImage } from '@rootnative/inertia/image' ``` ## Animatable keys `opacity`, `translateX`, `translateY`, `scale`, `scaleX`, `scaleY`, `rotate`, `rotateX`, `rotateY`, `width`, `height`, `borderRadius`, `tintColor`, `backgroundColor`, `borderColor`. ```tsx ``` --- # Motion.Pressable Animatable `Pressable`. The `gesture.pressed` sub-state connects directly to the `onPressIn` and `onPressOut` of Pressable, so it gets the touch slop and the accessibility behavior of React Native at no cost. ```tsx import { Motion } from '@rootnative/inertia' export function PrimaryButton({ onPress }: { onPress: () => void }) { return ( ) } ``` ## Tree-shaken import ```ts import { MotionPressable } from '@rootnative/inertia/pressable' ``` ## `style` must be a value, not a function This is the **most common trap** when you come from the `Pressable` of React Native. That `Pressable` accepts a function form, `style={(state) => ...}`, which runs on every press to derive styles from the press, focus, and hover state. The `createAnimatedComponent` wrapper of Reanimated doesn't call it, so the function would be dropped with no message. So `Motion.Pressable`, and every other `Motion.*` primitive, **throws in dev** when `style` is a function. ```tsx // ❌ Throws in dev. Drive press-state through `gesture` instead. [ styles.button, pressed && styles.buttonPressed, ]} /> // ✅ ``` The throw is behind `__DEV__`, so a production build doesn't pay for the check. A production build would still drop the styles with no message, and that is why the check in dev matters. This applies to `style` only. A plain value, an array, and the output of `StyleSheet.create` all work. If you need a conditional style that `gesture` can't animate, compute it once in render and pass the resulting style array. ## Notes - `gesture` is the only path. There is no separate pressable variant in the style of Moti. That is intentional. - `gesture.focused` works for any focusable Pressable (for example, with `accessible`, on TV, or with keyboard focus on web). When the platform sends no focus events, native ignores it with no error. See the full [gestures](../gestures) page for the sub-state priority and the type of the prop. --- # Motion.ScrollView Animatable `ScrollView`. The animations apply to the scroll **container** itself. Use it for an entrance transform, an exit fade, or a scale of the whole scrollable region. ```tsx import { Motion } from '@rootnative/inertia' export function AnimatedFeed() { return ( {/* rows */} ) } ``` ## Tree-shaken import ```ts import { MotionScrollView } from '@rootnative/inertia/scroll-view' ``` ## Notes - This primitive animates the outer container. To drive an animation from the scroll position itself (parallax, a sticky header), pair it with [`useScroll`](../api/hooks#usescroll). That hook returns the `scrollX` and `scrollY` shared values, plus an `onScroll` handler that you put on this primitive. - A per-row entrance animation belongs on a `Motion.View` row inside the scroll view, not on the scroll view itself. - This primitive mounts every child. [`Motion.FlatList`](./flat-list) is the virtualized counterpart, and it takes the same `useScroll` handler. Prefer it for a long or unbounded list. Keep this primitive for a short, fixed set of children. --- # Motion.FlatList Animatable, **virtualized** `FlatList`. This primitive lets one list both virtualize and animate. The `onScroll` handler of `useScroll` needs a scrollable that Reanimated animates. Before this primitive, the only animated scroller was [`Motion.ScrollView`](./scroll-view), which mounts every row. A long list had to pick one. Like `Motion.ScrollView`, the animations apply to the scroll **container**: the list frame, not the rows. A row animates through a `Motion.*` primitive inside `renderItem`. That is what makes a scroll-driven row effect work: ```tsx import { StyleSheet } from 'react-native' import { Motion, useScroll, useTransform, type SharedValue, } from '@rootnative/inertia' import { useAnimatedStyle } from 'react-native-reanimated' const ROW_HEIGHT = 72 const DATA = Array.from({ length: 400 }, (_, i) => ({ id: String(i), i })) function Row({ index, scrollY, }: { index: number scrollY: SharedValue }) { // Fade + lift each row as it approaches the top edge of the viewport. const top = index * ROW_HEIGHT const opacity = useTransform(scrollY, [top - 220, top - 80], [0.25, 1]) const shift = useTransform(scrollY, [top - 220, top - 80], [12, 0]) const rowStyle = useAnimatedStyle(() => ({ opacity: opacity.value, transform: [{ translateY: shift.value }], })) return } export function Feed() { const { scrollY, onScroll } = useScroll() return ( item.id} renderItem={({ index }) => } onScroll={onScroll} initial={{ opacity: 0, translateY: 16 }} animate={{ opacity: 1, translateY: 0 }} transition={{ type: 'timing', duration: 240 }} style={styles.list} contentContainerStyle={styles.content} /> ) } const styles = StyleSheet.create({ list: { flex: 1 }, content: { paddingHorizontal: 20, paddingVertical: 12, gap: 8 }, row: { height: 64, borderRadius: 10, backgroundColor: '#eef2ff' }, }) ``` `data` and `renderItem` keep their inference. The item type flows from `data` into `renderItem`. Independently, a `variants` map still narrows the string form of `animate`, so `animate="typo"` is a compile error here, the same as on every other primitive. ## Tree-shaken import ```ts import { MotionFlatList } from '@rootnative/inertia/flat-list' ``` ## Notes - The primitive is built on the `Animated.FlatList` of Reanimated, not on the `FlatList` of React Native. That wrapper injects the `CellRendererComponent` behind the per-row `itemLayoutAnimation`, and its default `scrollEventThrottle` is 1. So a `useScroll` handler on this primitive reports every frame with no extra prop. - `animate`, `initial`, and `gesture` animate the scroll container. A per-row entrance animation belongs on a `Motion.*` row inside `renderItem`. - The [`layout` prop](../layout) animates the list frame. Per-row layout animation is the own `itemLayoutAnimation` of Reanimated, which the primitive forwards unchanged. It can conflict with the measurement passes of the list, so measure the result before you adopt it. - Use this primitive instead of `Motion.ScrollView` whenever the row count is long or unbounded. `Motion.ScrollView` stays the correct choice for a short, fixed set of children. - Core doesn't wrap `FlashList`, because that would add a peer dependency. Wrap it yourself with [createMotionComponent](../api/create-motion-component), and set `scrollEventThrottle={1}` explicitly, because that patch belongs to Reanimated and doesn't come with the wrap. --- # Transitions The `transition` prop decides **how** an `animate` value reaches its target. The default is a spring tuned for everyday UI motion. Durations, decay, and instant assignment are opt-in. ## Top-level vs per-property `transition` accepts one config, which applies to every animating key, or a per-property map. A per-property entry always wins. ```tsx // One config, applies to all animating keys // Per-property — opacity uses timing, translateY uses spring ``` A per-property map can also carry config keys next to its entries. Those keys are the default for every key that the map doesn't name, and for each gesture layer with no entry of its own: ```tsx // Every key springs at 120 / 18, except opacity, which uses timing ``` An entry replaces the default whole. The two don't merge, so `opacity` above has no `tension`, and a `delay` in the default doesn't reach `opacity`. ## Named transitions Every place that accepts a config object also accepts a name from the nearest [``](./motion-config#named-transitions). That covers the top-level transition, a per-property entry, a gesture layer, the `layout` prop, and the value-layer hooks: ```tsx ``` An unknown name warns in development and falls back to the default spring. See [MotionConfig → Named transitions](./motion-config#named-transitions) for the merge rules and the typed-name augmentation. ## Types ### `'spring'` (default) A spring uses the react-spring vocabulary. The library converts it to Reanimated internally. The raw `stiffness` and `damping` names never appear in the public API. ```tsx transition={{ type: 'spring', tension: 170, // default friction: 26, // default mass: 1, // default velocity: 0, delay: 0, repeat: undefined, }} ``` #### Porting from raw Reanimated `stiffness` / `damping` The conversion is a **1:1 alias rename**, not a physics formula. If you have a tuned Reanimated `withSpring` config, port it: rename two keys. | Reanimated raw | Inertia | | -------------- | ---------- | | `stiffness` | `tension` | | `damping` | `friction` | | `mass` | `mass` | So a Material Design 3 emphasized spring (`{ stiffness: 380, damping: 32, mass: 1 }`) ports as `{ type: 'spring', tension: 380, friction: 32, mass: 1 }`. You don't retune it, and the motion looks the same. ### `'timing'` A timing transition interpolates over a duration. Use it for opacity fades and for any motion where a spring looks wrong. ```tsx transition={{ type: 'timing', duration: 250, // default easing: Easing.inOut(Easing.ease), // default delay: 0, repeat: undefined, }} ``` A custom `easing` function must be a worklet: put the `'worklet'` directive as the first statement of the function. The built-in `Easing.*` helpers of Reanimated and Inertia's `cubicBezier()` are worklets already. A plain function warns in dev. The fallback wrapper works on web, but a native build rejects it when the transition runs on the UI thread, because the closure of the wrapper holds the opaque plain function. An easing function must also be pure, with no captured JS-thread refs. ### Easing input shape `easing` accepts a plain function `(t: number) => number` or a Reanimated 4 `EasingFunctionFactory` (`{ factory: () => EasingFunction }`). The resolver detects the factory shape and unwraps it for you: ```tsx import { Easing } from 'react-native-reanimated' // Pass the factory directly — no `.factory()` call site needed. transition={{ type: 'timing', duration: 200, easing: Easing.bezier(0.2, 0, 0, 1), }} ``` Every place that takes `easing` accepts all three forms: a plain `(t: number) => number` function, an easing that is already a worklet, or a Reanimated factory such as `Easing.bezier(...)`. ### `cubicBezier()` — CSS easing tokens A design system usually stores its easing tokens in the W3C CSS format. `cubicBezier` builds an `easing` value from any of the three CSS spellings, so you can use a token file as it is, with no `Easing.bezier` calls: ```tsx import { cubicBezier } from '@rootnative/inertia' cubicBezier(0.2, 0, 0, 1) // number form cubicBezier('cubic-bezier(0.2, 0, 0, 1)') // CSS token form cubicBezier('ease-out') // CSS keywords, incl. 'linear' transition={{ type: 'timing', duration: 200, easing: cubicBezier(theme.motion.easingStandard), }} ``` The keywords map to their canonical css-easing-1 curves (`ease`, `ease-in`, `ease-out`, `ease-in-out`). `linear` maps to the identity easing. Invalid input throws at call time, so a malformed token fails at theme setup and doesn't animate with the wrong curve. As in the CSS spec, `x1` and `x2` must be within `[0, 1]`, and `y1` and `y2` can overshoot. The stepping keywords (`step-start`, `step-end`) and the CSS `linear(...)` function are not supported. Together with [named transitions](./motion-config#named-transitions), this is the recommended way to feed the motion tokens of a theme into Inertia: ```tsx ``` ### `'decay'` A decay starts from a velocity and slows down, like a flick. Combine it with `react-native-gesture-handler` for scroll-style flick momentum. ```tsx transition={{ type: 'decay', velocity: 800, deceleration: 0.998, clamp: [0, 600], }} ``` A decay can't repeat. A decay config ignores `repeat`. ### `'no-animation'` This type skips the interpolation and jumps to the target value. It equals a direct shared-value assignment, but it stays inside the transition shape, so per-property overrides compose: ```tsx transition={{ opacity: { type: 'timing', duration: 200 }, translateY: { type: 'no-animation' }, }} ``` Reduced-motion mode also swaps every transition into this type. See [MotionConfig](./motion-config). ## `delay` Every type except `'no-animation'` takes `delay`. The delay runs before the animation starts: ```tsx transition={{ type: 'spring', delay: 200 }} ``` ## `repeat` `repeat` has one shape, with no separate flags. See [sequences and repeat](./sequences#repeat) for the full table. ## Defaults | Type | Field | Default | | ------ | ---------- | --------------------------- | | spring | `tension` | `170` | | spring | `friction` | `26` | | spring | `mass` | `1` | | timing | `duration` | `250` | | timing | `easing` | `Easing.inOut(Easing.ease)` | The source of truth for the spring rows is `DEFAULT_SPRING` in `packages/core/src/transitions/spring.ts`. The source of truth for the timing rows is `packages/core/src/transitions/resolve.ts`. --- # Sequences and repeat Per-property keyframes and loops use two related shapes: an array for the sequence steps, and the one `repeat` config on a transition. ## Keyframes Pass an array as the value of an animatable key to step through the frames in order: ```tsx ``` Each step inherits the transition of that key. A sequence runs on the UI thread and never goes through JS. ## Per-step transitions Replace a step with `{ to, ...transitionOverride }` to give that step its own transition: ```tsx ``` The key is `to`, not `value`, because a step describes a destination: "animate **to** this". ## Repeat `repeat` is part of the transition, not of `animate`. It has one shape, with no separate `loop` or `repeatReverse` flags. | Form | Meaning | | ------------------------------------------ | ---------------------------------------------- | | `repeat: 3` | Run 3 iterations total, alternating direction. | | `repeat: 'infinite'` | Loop forever, alternating direction. | | `repeat: { count: 3, alternate: false }` | Full control. `alternate` defaults to `true`. | | `repeat: { count: 'infinite', alternate }` | Endless with explicit alternate flag. | ```tsx ``` On a sequence, `repeat` wraps the **whole sequence**, not each step. A `repeat` inside a step applies only inside that step. `count` is the total number of iterations, including the first pass, so `repeat: 2` plays the animation twice. A count below `1` runs the animation once and warns in dev. Inertia doesn't forward that count to Reanimated, which reads a count of `0` as endless. `alternate` has no effect on a sequence. The `reverse` flag of Reanimated only swaps the target of the wrapped animation, and a sequence ignores that. Every pass starts again at the first step. To alternate, write the reverse steps into the sequence: `[0, 80, 0]` instead of `[0, 80]` with `alternate`. An explicit `alternate: true` on a sequence warns in dev. A `'no-animation'` or `'decay'` config ignores `repeat`. ## Reduced motion A sequence under the reduced-motion gate doesn't play. The property snaps to the **last keyframe**, where the sequence would end, and Inertia builds no `withSequence`. Inertia also drops `repeat` and `delay`, so an endless sequence rests and doesn't loop. ```tsx // reduce-motion on at the OS level: opacity settles at 0.25, nothing animates. ``` Write the keyframes so that the last one is the state that a reduce-motion user must see. A loop that returns to its start (`[0, 80, 0]`) already does that. A loop written as one leg plus `alternate` can't, because [`alternate` has no effect on a sequence](#repeat). For a drift between two states, use one target and let `repeat` alternate it: ```tsx // Oscillates between -8 and 0, and rests at 0 under reduced motion. ``` See [`MotionConfig`](./motion-config) for how Inertia resolves the gate. ## `onAnimationEnd` One callback reports the lifecycle of a sequence and of a repeat: ```tsx { // phase: 'step' | 'sequence' | 'repeat' | 'animation' // step: index in the keyframe array, undefined for non-sequences // iteration: 0 on the first pass, 1 on the second, … }} /> ``` | `phase` | When it fires | | ------------- | --------------------------------------------------------------------- | | `'step'` | A non-final step in a sequence settles. | | `'sequence'` | Last step of a non-final iteration — the sequence is about to repeat. | | `'repeat'` | A non-final iteration of a non-sequence animation completes. | | `'animation'` | The terminal phase of the property — no more passes will run. | A transform fires once per logical event, not once per axis. A `translateX` and `translateY` animation on the same primitive gives one callback for the transform, not two. When the terminal `'animation'` phase fires for a transform key, `key` is the sentinel `'transform'`. The mid-step events (`'step'`, `'sequence'`, `'repeat'`) still fire per axis, with the axis name (`'translateX'`, `'scale'`, and so on), because each step is its own logical event. An endless axis is not part of that group. A property with `repeat: 'infinite'` never reaches `'animation'`: it emits `'repeat'` forever. So Inertia excludes it from the transform group, and it doesn't hold the group open. Give `translateX` an infinite repeat and `translateY` a finite one, and you still get the terminal `'transform'` callback when `translateY` lands. Make _every_ transform axis infinite, and no terminal callback fires, because nothing finishes. The same rule protects [``](./presence). An endless `exit` animation never settles, so it doesn't gate the unmount. If every exiting property repeats forever, `Presence` removes the child at once. If some properties are finite, those still gate the unmount. A top-level `transition={{ repeat: 'infinite' }}` also applies to `exit`. If you also want a normal exit, scope the repeat to the property that must loop: `transition={{ opacity: { repeat: 'infinite' } }}`. --- # Variants A variant is a named animation state. Define the states once, then pass a key to move between them. The common case needs no hook. ## Declarative ```tsx import { Motion } from '@rootnative/inertia' const variants = { closed: { translateY: 100, opacity: 0 }, open: { translateY: 0, opacity: 1 }, } as const export function Sheet({ isOpen }: { isOpen: boolean }) { return ( ) } ``` The variant keys autocomplete on `animate`, and a typo is a compile error. You need no type annotation: TypeScript infers the keys of the map at the JSX call site. `as const` is optional. Add it only when you also want the variant _values_ readonly. ## Programmatic — `useVariants` Use a controller when you chain states, await a transition, or set a variant from code outside React (an event handler, a gesture callback, a network response). Build the controller with `useVariants` and pass it through the `controller` prop: ```tsx import { Motion, useVariants } from '@rootnative/inertia' const variants = { resting: { scale: 1, opacity: 1 }, loading: { scale: 0.96, opacity: 0.6 }, done: { scale: 1.04, opacity: 1 }, } as const export function SaveButton() { const controller = useVariants(variants, 'resting') async function save() { controller.transitionTo('loading') await api.save() controller.transitionTo('done') } return ( ) } ``` `useVariants(variants, initial?)` returns a `{ current, transitionTo }` controller. `current` is the active key. `transitionTo(next)` applies the matching variant on every Motion primitive that holds the controller. The controller also carries an internal `subscribe` for the primitives. `subscribe` is not part of the public contract. When a primitive has both `controller` and `animate`, the controller wins. Don't mix them. The typed contract is: drive a primitive from a controller, or from `animate`, not both. ## Variant transitions `transition` comes from the Motion primitive, not from each variant. One transition on the primitive applies to every variant target: ```tsx ``` A different transition per variant target isn't supported. If you need that, switch the `transition` of the primitive on the active key. --- # Gestures Every Motion primitive has one `gesture` prop. There is no `whileTap` or `whilePress` family, and no separate "pressable" variant. When you omit the prop, Inertia mounts no handlers, so the prop has zero overhead. ```tsx ``` ## Sub-states | Sub-state | Active when | Backed by | | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `pressed` | Any pointer is down on the component — finger, mouse, or pen — until it lifts or the gesture is cancelled. | `onTouchStart` / `End` / `Cancel`, `onPointerDown` / `Up` / `Cancel` (web), plus `onPressIn` / `onPressOut`. | | `focused` | The component owns focus, regardless of how it arrived (mouse, touch, or keyboard). | `onFocus` / `onBlur`. | | `focusVisible` | The focus shows a ring (W3C `:focus-visible`): on web, the browser's `:focus-visible` for the focused element; keyboard focus everywhere. On native — where focus always arrives via D-pad / hardware keyboard / screen reader — behaves identically to `focused`. | `onFocus`, which asks the focused element whether it matches `:focus-visible`. A module-level input-modality tracker (web `keydown` vs `pointerdown` / `mousedown` / `touchstart`; a ⌘, Ctrl or Alt chord does not count) is the fallback when the event has no focused target or the browser does not support the selector. The tracker's `document` listeners attach when the first component that declares `focusVisible` mounts, not at import, so the package stays `sideEffects: false`. | | `hovered` | Pointer is over the component. **Web-only**, no-op on native. | `onMouseEnter` / `onMouseLeave`. | A sub-state layers over the base `animate` target, property by property. When a sub-state releases, the property animates back to the value in `animate`. If `animate` doesn't set that property, the property rests at **the value in your static `style`**. So the focus ring above returns to the `borderColor` of the stylesheet of the element. You don't have to repeat a resting value in `animate` only because a sub-state names it: ```tsx const styles = StyleSheet.create({ field: { borderColor: '#d4d4d8', borderWidth: 1 }, }) // Rests at #d4d4d8, animates to #4f46e5 on focus, returns to #d4d4d8. ``` When neither `animate` nor `style` gives a value, the property falls back to its type default (`0` for a number, `transparent` for a color). The same rule covers `exit` targets and a property that appears in only some `variants` branches. A key that any of them names joins the animated set, but it rests on your style until something drives it. Use `focused` for a state-layer fill (any focus, including click focus on web) and `focusVisible` for a focus ring. Declare both, and you get the correct behaviour: a click on a button shows the state layer, and a tab to the button shows the state layer **and** the ring. ### `focusVisible` follows the browser on web In the focus event, Inertia asks the focused element whether it matches `:focus-visible`. So the ring shows where the browser would draw its own focus outline, and an app that removes that outline loses no indicator. The browser knows cases that no input tracker sees. For example, after a click that focuses nothing, Chromium marks the next focus that a script moves as `:focus-visible`. A text input matches `:focus-visible` after a click too, because the browser draws its outline there. The input-modality tracker is the fallback in three cases: a call with no event, a focus event that a script dispatches (it moves no focus), and a browser without `:focus-visible`. If you call a [`useGesture`](./api/hooks#usegesturetransition) `onFocus` yourself, pass the event: `handlers.onFocus(event)`. **In jsdom tests**, `:focus-visible` matches every focused element, so a test that calls `element.focus()` always sees the ring. `fireEvent.focus` moves no focus and gets the fallback: fire a `keydown` or a `pointerdown` on `document` first to set the modality. ### Write `pressed` relative to rest, not to `hovered` `hovered` never activates on a touch device. So a `pressed` target that only makes sense as a step down from `hovered` makes **no motion at all** on native: ```tsx // Wrong on native: pressed is value-identical to rest, so nothing animates. ``` On web this works: hover lifts the card, and press settles it. On iOS and Android there is no hover layer, so the cascade runs from rest to `pressed`, and the two values are the same. The animation does nothing, and nothing warns you, because a target equal to the resting value is valid. Write each sub-state as an absolute target from **rest**. Treat `hovered` as an intermediate step that only some platforms see: ```tsx // Right: every layer differs from rest, so each one moves on every platform. ``` The general rule: **check each sub-state against rest on its own**, because that is the only comparison that a touch device makes. ## Priority When several sub-states are active at once, they composite as a **priority cascade** in this order. A later layer composites over an earlier one: `hovered` → `focused` → `focusVisible` → `pressed` Each declared sub-state owns a progress shared value (0 to 1). The value fades in when the sub-state activates and fades out when it releases. The `useAnimatedStyle` worklet composites the layers per property: ``` v = base v = lerp(v, hovered.value, progressHovered) // if declared v = lerp(v, focused.value, progressFocused) // if declared v = lerp(v, focusVisible.value, progressFocusVisible) // if declared v = lerp(v, pressed.value, progressPressed) // if declared ``` A color key uses `interpolateColor` instead of `lerp`. When one sub-state is active, the rule is: the declared layer with the highest priority wins. A `pressed` target overrides every layer below it. The gain of layered composition shows in **overlapping transitions**. When you release a press while the pointer still hovers, the press layer fades back to 0 on its own, while the hover layer stays at 1. So the value lands on the hover target and doesn't snap back to the base. ## Per-layer transitions Each layer animates with its own transition. Inertia resolves it in this order: 1. `transition.` on the primitive (for example `transition.pressed`) 2. The top-level `transition`, when you write it as a top-level transition object 3. The library default (a spring) ```tsx ``` Per-layer entries (`pressed`, `hovered`, …) and per-property entries (`backgroundColor`, `opacity`, …) share the same `transition` map. They don't conflict, because no gesture-layer name is a valid style prop. ## Type inference A `gesture` sub-state has the same `style`-derived type as `animate`. So `tintColor` autocompletes inside `gesture.pressed` on `Motion.Image`, and `Motion.View` rejects it. ## Composing user handlers Inertia composes its internal handlers with the handlers that you attach: ```tsx analytics.track('press', event)} gesture={{ pressed: { scale: 0.96 } }} /> ``` Your `onPressIn` runs first, then the internal pressed-state setter. The same order applies to every event that the gesture prop subscribes to. ## When the prop isn't enough — `useGesture` The `gesture` prop animates the own style of the primitive. Sometimes the gesture state of one Pressable must drive **several** animated views: a focus ring as a sibling, an MD3 state-layer halo over the content, a separate icon-color animation. Then use [`useGesture`](./api/hooks#usegesturetransition), the hook form of this prop. It returns the progress shared values (0 to 1) for `pressed`, `focused`, `focusVisible`, and `hovered`, plus a set of handlers to spread on a `Pressable`. Feed the shared values into as many `useAnimatedStyle` blocks as you need. ```tsx const { pressed, focused, hovered, handlers } = useGesture() // ...drive a focus ring, a halo, a tint — each from the same gesture state {children} ``` The prop and the hook share the layered-blend model, the `isFocusVisible()` rules, and the `` gate. They are the same machinery with two surfaces. ## When you want MD3 state-layer overlays — `useGestureLayer` The `gesture` prop composites states as a fixed **priority cascade**. When hovered and pressed are both fully active, the value converges to the `pressed` target, because `pressed` is highest in the cascade, whichever target is numerically stronger. An MD3 state-layer halo or an iOS translucent overlay wants a different model: **clamped-max**. There, hovered plus pressed shows the _stronger_ target per key, whatever its priority. [`useGestureLayer`](./api/hooks#usegesturelayerstates-options) at `@rootnative/inertia/gesture-layer` is the convenience layer for that model. You supply a target map per state (`rest`, `hovered`, `focused`, `focusVisible`, `pressed`, `disabled`). The hook owns the worklet, the disabled override, and the transition. ```tsx import { useGestureLayer } from '@rootnative/inertia/gesture-layer' const { style, handlers } = useGestureLayer({ rest: { opacity: 0, backgroundColor: 'transparent' }, hovered: { opacity: 0.08, backgroundColor: '#000' }, pressed: { opacity: 0.12, backgroundColor: '#000' }, }) ``` A numeric key composes with clamped-max. A color key composes with the priority cascade (`hovered → focused → focusVisible → pressed`). `disabled` sits on top of both. The result also carries `states`, the progress shared values (0 to 1) per state behind the composed style. So an extra style can derive from the same gesture wiring without a second `useGesture` call, for example `useShadow({ from, to, progress: states.hovered })` for an elevation crossfade. Use plain `useGesture` when the composition model doesn't fit (an additive blend, a multiply, a custom rule per key). ## When you need drag, pan, or swipe The `gesture` prop covers Pressable-shaped states: active, inactive, focused, and hovered. For a continuous gesture with a value (a thumb that follows the finger, a sheet that flicks closed, a carousel with momentum), use the [gestures adapter](./gestures-adapter): `useDrag`, `usePan`, and `useSwipe`. It's an opt-in sibling package, so the core library has no `react-native-gesture-handler` peer for an app that only animates buttons. A fully gesture-driven `Slider` is the canonical example that the core package can't build alone. The position of the thumb has to follow the touch X continuously, and that is what the adapter is for. --- # Presence `` keeps a child mounted long enough to play its `exit` animation after you remove the child from the tree. It has the same role as `` in Framer Motion, with a smaller API. ```tsx import { Motion, Presence } from '@rootnative/inertia' export function Toast({ visible }: { visible: boolean }) { return ( {visible ? ( ) : null} ) } ``` ## How it works When a child disappears from the `children` array, `Presence` takes a snapshot of it and holds the snapshot in a JS-thread map. `Presence` unmounts the child after the child finishes its exit animation and calls `safeToRemove()`. `Presence` does **not** use the `entering` and `exiting` lifecycle of Reanimated. The exit frames are ordinary Motion animations that the `exit` prop of the child drives. That design lets an interrupted exit reverse smoothly when the child re-enters. ## Required: `key` Every direct child of `` must have an explicit `key`. Without a key, React uses the position as the identity, and a removal looks like a prop change. Then there is nothing to mark as exiting. `Presence` never renders a child with no key. A dev build also logs a warning. A production build drops the child with no message. ## Tap-deaf exits When a child starts its exit animation, Inertia merges `pointerEvents: 'none'` into its style. A tap falls through to the element below. It doesn't start the node that is about to unmount again. In other libraries, this is the "two taps to open the popover again" defect. In Inertia you need one tap. ## Re-entry interrupts exit If a key reappears in `children` while its child exits, the exit animation reverses toward the `animate` values. The component instance stays alive through the round trip, with no remount and no flicker. ## Multiple children `Presence` handles lists too: ```tsx {items.map((item) => ( ))} ``` Each child has its own exit timing. One row can finish its exit while another row still animates in. An exiting child animates out **in place**. It keeps its slot among its siblings until `Presence` removes it, right after its nearest sibling that stays. When you delete the middle row of a list, that row fades where it is. The rows below it don't move up during the animation. A sibling that you add or reorder while a child exits goes around the exiting child. Several adjacent exiting children keep their order. ## Nested `Motion.*` children An exiting child stays mounted until every `Motion.*` inside it finishes its exit. A nested `Motion.*` with no `exit` finishes at once, so it doesn't cut the exit of the child that holds it. A nested `Motion.*` with a longer `exit` holds the child until that exit ends. ```tsx {open ? ( {/* No `exit`: the sheet still slides out in full. */} {/* A shorter `exit`: it fades, and the sheet keeps sliding. */} ) : null} ``` So a component that animates on its own, such as a spinner or a skeleton, can go inside a sheet or a dialog with no `exit` of its own. A custom component that calls `usePresence()` and then `safeToRemove()` removes the child at once. `safeToRemove()` doesn't wait for the `Motion.*` exits, so call it only after the whole exit finishes. ## A child with no `Motion.*` leaves at once A departing child with no `Motion.*` and no `usePresence()` consumer has nothing to animate and nothing to wait for. `Presence` removes it at once, with no exit animation. So a loading placeholder in a plain `View` can swap for its content under one ``: ```tsx {loading ? ( ) : ( )} ``` The content fades in, and the placeholder is gone on the same frame. Give the placeholder a `Motion.View` with an `exit` when it must fade out. ## What can be a child? Any element. A child animates its exit through a `Motion.*` primitive, or through a component that calls `usePresence()` and then `safeToRemove()` when its exit finishes. `Presence` removes a child with neither at once. ## Accessing presence state A custom component can read the presence state: ```tsx import { usePresence } from '@rootnative/inertia' function MyExitable() { const presence = usePresence() // presence is null when no ancestor exists // presence?.isPresent flips false when the parent removes us // presence?.safeToRemove() once the exit animation finishes } ``` --- # Stagger `` gives each child an animation delay that comes from the position of the child. A list entrance then cascades, and no child computes `index * ms` itself. The parent owns the timing, because the parent decides the order. ```tsx import { Motion, Stagger } from '@rootnative/inertia' export function GiftList({ revealed, gifts }: Props) { return ( {gifts.map((gift) => ( ))} ) } ``` Child `i` (in render order) gets a delay of `delay + i * interval` milliseconds. The delay applies to the declarative animations of every `Motion.*` primitive in the subtree of that child: the mount animation (`initial` to `animate`) and each later `animate` change. `` renders no host view of its own, only a context for each child. ## Props | Prop | Type | Default | Meaning | | ---------- | ------------------- | --------- | --------------------------------------------------------------------- | | `interval` | `number` | required | Milliseconds between consecutive children. | | `delay` | `number` | `0` | Base delay added to every child, so the whole cascade can start late. | | `from` | `'first' \| 'last'` | `'first'` | Which end of the list starts the cascade. `'last'` reverses it. | | `enabled` | `boolean` | `true` | Turn the stagger off in one place — every child gets a delay of `0`. | ## Why the parent owns the timing The alternative, `transition={{ delay: index * 60 }}` on each child, has two structural problems. This component removes both: - **The index is per-child state.** A list that filters, reverses, or reorders staggers from stale positions, unless every child guards its own delay. `` computes every delay again from the current render order on every render. - **You can't turn the cascade off in one place.** The common requirement is "cascade in, but snap out together". Pass `enabled={revealed}`. The hide direction then animates with no delays, while the reveal cascades. ## What the delay applies to The stagger delay wraps the **declarative animations** of the child: everything that `animate` drives, including the initial mount. It adds to the own `transition.delay` of the child. The delay does **not** apply to: - **`gesture` sub-states.** Press and focus feedback with a delay from the list position would look like lag, not like choreography. - **`` exits.** An exit with a delay from the position would hold the unmount until the cascade ends. Exits run on their own timing. Use `enabled` if you want the hide direction to snap together. - **Reduced motion.** When `` gates a subtree, values snap at once. A delayed snap is still motion choreography, and that is what the user asked to turn off. ## Details to know - **Positions come from the render order after filtering.** `` drops `null`, `undefined`, and boolean children before it assigns positions, so a conditional child leaves no hole in the cascade. - **The delay reaches nested primitives.** Each child slot gets its own provider, so a `Motion.View` anywhere inside the subtree of child `i` inherits the delay of child `i`. The inner animated parts of a list row cascade with their row. - **A delay change alone starts nothing.** Inertia reads the delay when an animation starts. A change of `interval`, `from`, or `enabled` affects the next animation, not an animation in flight. - **A custom animated component can take part.** `useStaggerDelay()` returns the delay of the current child slot (`0` outside a ``). Add it to the delay of whatever you resolve through `resolveTransition` or `resolveAnimatableValue`. ## A list that cascades in and whose rows exit `` and `` each read their own direct children, so one can't wrap the other around the same list. `` gives `` one child. `` gives every row the delay of one slot. Give each row its own `` with one child, and compute the delay from the index: ```tsx import { Motion, Presence, Stagger } from '@rootnative/inertia' export function BuildList({ builds }: Props) { return ( {builds.map((build, index) => ( ))} ) } ``` - **The `key` goes on the ``.** `` follows its direct children, and here those are the `` elements. - **The rows cascade in.** Row `index` starts `index * 40` milliseconds late. - **A removed row exits with no delay.** It stays mounted until its exit ends, as with any `` child. - **The rows that stay don't replay.** A removal changes the index of each later row, but a delay change alone starts nothing. - **A row that you add later gets the delay of its index too.** If a late row must come in at once, pass `delay={0}` after the first cascade. - **`from` and `enabled` are yours to compute.** Use `(builds.length - 1 - index) * 40` for a cascade from the last row, and `0` for no cascade. ## Nesting Nested `` components don't add up. The nearest ancestor wins, the same as any React context. Give an inner list its own ``, and its children cascade relative to that list. --- # Layout The `layout` prop animates a change of position or size that comes from outside the `animate` flow: a flex sibling that grows, a list that reorders, a column that changes its width. Without the prop, those changes snap. With the prop, they interpolate. ```tsx import { Motion } from '@rootnative/inertia' function ReorderableRow({ item, onPress }: Props) { return ( ) } ``` Internally, the prop resolves to the `LinearTransition` builder of Reanimated. The prop takes the same react-spring vocabulary (`tension`, `friction`, `mass`) as `transition`. The raw Reanimated names (`stiffness`, `damping`) never appear in the public API. ## Accepted shapes | Value | Meaning | | ------------------ | ----------------------------------------------------------------------------------------------- | | omitted / `false` | No layout animation. Position and size changes snap (default). | | `true` | Library default spring (`tension: 170`, `friction: 26`, `mass: 1`). | | `TransitionConfig` | `'spring'` or `'timing'`. `'decay'` downgrades to spring; `'no-animation'` skips the animation. | ```tsx // default spring // custom spring // duration-based t * t }} /> // custom easing ``` A custom easing function must be a worklet, the same as `transition.easing`. Add the `'worklet'` directive as the first statement of the function. A plain function warns in dev and works on web only. ## What triggers a layout animation `LinearTransition` fires when the measured frame of the native view changes between two commits. The common triggers: - The siblings of the component reorder in a flex container. - The size of the component changes because its `style` props swap (`height: 56` to `height: 96`). - The position of the component moves because a sibling grew, shrank, or appeared. The `animate` flow is independent. A `Motion.View` can have both `animate={{ opacity }}` and `layout`. The opacity runs through `useAnimatedStyle`, and the layout runs through the native commit hook of Reanimated. The two don't conflict. ## Reduced motion `layout` follows [``](./motion-config.md). When reduced motion is active, the prop resolves to no builder, and changes snap. Inertia passes `undefined` to the component, not a `.duration(0)` builder, because Reanimated still tracks commits for a builder. The snap path is cheaper. ## Shared element transitions (`layoutId`) The `layoutId` prop is a separate but related mechanism. It moves one logical element between two screens or two layouts. ```tsx // Screen A // Screen B (after navigation) ``` The first `Motion.View` unmounts. A second `Motion.View` with the same `layoutId` mounts within about 1 second. The new element then runs a FLIP animation into place, from the rect that the first element measured as it unmounted. That is a hero transition with no animation config beyond the shared id. How `layoutId` differs from `layout`: - `layout` animates the changes of size and position of **this** element between commits. It needs no id. - `layoutId` animates from the last rect of **another** element to the current rect of this element, across a mount or a screen. The `transition` prop of the **incoming** element controls the FLIP animation. The default is a spring. `'timing'` works. `'decay'` downgrades to a spring. Reduced motion skips the transition. The outgoing element gives only its last rect and its style snapshot. The `transition` must be a top-level transition object (`transition={{ type: 'timing', duration: 250 }}`). The entries of a per-property map don't reach the FLIP. If the map also carries config keys, such as `{ type: 'timing', duration: 250, opacity: { … } }`, the FLIP uses those keys. Otherwise the default spring applies. The FLIP reads `duration`, `easing`, and `delay` of a timing transition, and `tension`, `friction`, `mass`, `velocity`, and `delay` of a spring. A `delay` holds the element at the source rect before it moves. `repeat` doesn't apply. ### Style carry The rect FLIP moves and scales the element. A hero card that also changes its color or its corner radius between screens would snap on those props while its frame animates. That is the most visible half of the transition. So Inertia carries a set of style keys from the source and crossfades them out over the same transition: | Carried | Not carried | | --------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `opacity`, `borderRadius`, `backgroundColor`, `borderColor`, `color`, `tintColor` | Transform keys (the FLIP owns them — carrying them too would double-apply the displacement), `shadowColor` (crossfading one of four native shadow props over snapped geometry looks worse than letting the shadow snap whole), everything else | ```tsx // Screen A — a small tile // Screen B — a large header. Radius and color crossfade with the rect. ``` There is nothing to configure. The carry uses the existing `layoutId` and `transition` props. There is no key list to override and no `layoutStyles` prop. If you need a key that Inertia doesn't carry, drive it from `animate` on both sides. Rules to know: - **A key takes part only when the element already has a value for it**, from `animate`, `initial`, a variant, `gesture`, or its static `style`. Inertia never invents a value. A key that the element says nothing about would rest at the generic type default. For `color` on a `Motion.Text` that inherits its color from a parent, that default is `'transparent'`: invisible text on an element that you only asked to move. - **Inertia ignores a key that one side lacks, in both directions.** A key that the source carried but the target has no value for does nothing, and the reverse is also true. - **Inertia reads a source that is still mounted live**, for the same reason that it measures its rect again: its values move without a layout pass. After the source unmounts, only the snapshot from the unmount remains. - **The carry overrides `initial` for the carried keys** on the mount that consumes a source. The carry composites above the base value, so the first frame shows the color of the source, whatever `initial` asked for. - **Reduced motion and `'no-animation'` snap**, the same as the rect path. A coordinate-space mismatch also snaps: half a shared-element transition looks like a glitch, not like a fallback. ### Caveats and current scope - **Window coordinates, where the host can supply them.** Inertia measures a rect with `measureInWindow`, which resolves synchronously on the New Architecture (Fabric). On web, react-native-web answers `measureInWindow` from a `setTimeout`, so Inertia reads the `getBoundingClientRect()` of the DOM node instead. That is the same window rect, read synchronously. So a source and a target can sit under containers at different screen offsets and still line up. Where a synchronous measurement isn't available, both fall back to the parent-relative coordinates that `onLayout` reports. That is the case on the legacy architecture, where `measureInWindow` answers over the bridge, and for a node that already detached. The fallback is consistent, but it doesn't see the offsets of the parents. So a setup with nested parents lines up only on Fabric and on web. - **Mixed coordinate spaces skip the transition.** A source in one space and a target in the other aren't comparable: the delta would be off by the window offset of the parent. Inertia skips the animation and lets the element appear at its natural position. It doesn't move the element in from the wrong place. - **Inertia measures a source that is still mounted again on demand.** `onLayout` doesn't fire when an _ancestor_ scrolls, so a stored window rect drifts while the element hasn't moved relative to its parent. When the FLIP starts, Inertia asks a source that is still mounted for a current measurement, instead of the stored one. That is the usual case: a stack navigator keeps the previous screen alive below. So a scroll of a list before a tap on a row doesn't offset the transition. The FLIP starts as the target mounts, or on its first layout where Inertia can't measure the target yet. After the source unmounts, only the rect from the unmount remains. If the navigator already moves the outgoing screen, the new measurement catches the screen mid-transition, as far as the transition has moved. - **A source measures itself as it unmounts.** A transform moves an element without a layout pass, so `onLayout` doesn't report it. A source that entered with `initial={{ scale: 0.4 }}` lays out once, mid-entrance, and that rect is too small. Inertia measures the rect that the next mount consumes in the unmount cleanup, while the node is still attached, so the rect has the final transform in it. The last layout rect is the fallback when Inertia can't measure the node. - **A native stack push can hide the FLIP on iOS.** The native stack slides the new screen in, and the target mounts while that slide still moves the screen. On an iOS simulator with the native stack of Expo Router, the target appeared at its final size on the first frame of the new screen, with no FLIP. Android is not measured. To show the FLIP, present the target screen with no native animation, so that the FLIP is the transition: ```tsx ``` - **One mount per id.** Two `Motion.*` primitives with the same `layoutId` mounted at the same time is undefined behavior. The most recent layout commit wins as the source for the next consumer. - **TTL.** A source that is still mounted stays valid as long as it is mounted. A list card that laid out once and then sat still for a minute is as good a source as one that laid out a frame ago, because Inertia can measure it again. A rect that a source recorded on unmount is valid for about 1 second. A new mount in the same render as the unmount, such as a grid card that a detail header replaces, takes the rect when it mounts, before its first layout. So a slow device doesn't cancel the FLIP. If the new mount lands later (a slow navigation, a paused transition), no FLIP runs. The element then appears at its natural position. - **In tests.** The `measureInWindow` of the Jest host mock never calls its callback, so a test suite always sees the parent-relative path. That is intentional: it keeps the `layoutId` behavior in tests stable and independent of measurement. ### Why not `sharedTransitionTag`? Reanimated 4 removed `sharedTransitionTag` and `SharedTransition`. `layoutId` is the Inertia replacement. It's a JS-side measure registry, not a native handoff, so it needs no native screen-transition harness. It works with any navigator (React Navigation, Expo Router, or your own) that mounts and unmounts screens. ## What `layout` doesn't do (yet) - **Per-axis control (`layout="position"` or `layout="size"`).** `LinearTransition` has no axis filter: the whole frame animates together. If you need to control one dimension, animate it through `animate` instead. - **Layout callbacks.** `onAnimationEnd` fires for `animate` keys, not for layout commits. The `withCallback` of Reanimated backs that on the layout side. Inertia doesn't expose it yet. ## Caveats - The wrapped component must render a native host view. Every `Motion.*` primitive does. If you wrap a custom component with `createMotionComponent(C)`, make sure that `C` renders a host view. Otherwise the prop does nothing. - A layout animation on a virtualized list item (a FlatList row) can conflict with the measurement passes of the list. Measure the result before you add `layout` to a row component. Use the [Perf bench](./perf-bench.md) screen to test it. --- # MotionConfig A provider for the animation config of a subtree. It sets how the Motion primitives below it respond to the reduce-motion accessibility setting of the OS, and it holds a registry of [named transitions](#named-transitions) that you can use anywhere a transition config is accepted. :::tip Free accessibility win when you migrate An app that moves from hand-written `useSharedValue` and `useAnimatedStyle` code to the Inertia primitives gets reduce-motion support for free. Every `Motion.*` component reads the OS setting through [`useShouldReduceMotion()`](#reading-the-resolved-value), with no setup per component. If you had no reduce-motion handling before, you have it now. ::: ## Default — respect the OS By default, and with no provider in the tree, Inertia respects the reduce-motion setting of the OS. When the user enables it, Inertia swaps every per-key transition for `'no-animation'`, and values snap to their target at once. A sequence still iterates, but each step settles at once. ```tsx import { MotionConfig } from '@rootnative/inertia' export function App() { return {/* Your app */} } ``` `reducedMotion="user"` is the default value of the prop. An explicit wrapper around the root only documents the intent, because the same happens with no provider. ## Modes | Value | Behavior | | ---------- | -------------------------------------------------------------------------------------------- | | `'user'` | Defer to the OS accessibility setting. The right default for app-level wrappers. | | `'never'` | Animate regardless of the OS setting. Use sparingly — e.g. essential onboarding transitions. | | `'always'` | Never animate, regardless of OS setting. Useful for tests and snapshots. | ## Scope `` is a context provider. Wrap a subtree to override the behavior there: ```tsx ``` A nested provider **inherits** from its ancestor. A provider that omits `reducedMotion` keeps the mode of the ancestor, and the `transitions` maps merge per name, with the child first. A provider with only `transitions` in the middle of the tree never disturbs an outer `reducedMotion` override. ## Named transitions `transitions` registers named transition configs for the subtree. Every place that accepts a `TransitionConfig` also accepts a registered name: the `transition` prop (top-level, per property, **and** per gesture layer), the `layout` prop, and the value-layer hooks (`useAnimation`, `useSpring`, `useBooleanSpring`, `useGesture`, `useGestureLayer`). ```tsx {/* Anywhere below the provider: */} ``` ```ts const progress = useBooleanSpring(checked, 'selection') const fade = useAnimation(visible ? 1 : 0, 'state-hover') ``` The names are **your** vocabulary: design-system tokens, semantic roles, or whatever your app standardizes on. Inertia ships no presets. The registry lets a theme file (MD3, iOS style, Fluent, or your own) be the one source of truth for motion values, instead of copied config objects at every call site. The rules: - **The nearest provider wins.** A name resolves against the merged registry of all ancestor `` providers. - **Nested providers merge.** The `transitions` map of a child provider merges into the ancestor registry. The child overrides an entry with the same name. - **An unknown name degrades softly.** An unregistered name warns in development and falls back to the library default spring. The animation still runs. - **A spring-only hook stays spring-only.** `useSpring` and `useBooleanSpring` accept a name, but a name registered as `timing`, `decay`, or `no-animation` warns in dev and falls back to the default spring. Use `useAnimation` when the type of the named transition must apply. ### Typed names (optional) By default, any string is accepted where a name is (`TransitionName` is `string`). To get autocomplete and a compile-time typo check, augment the `RegisteredTransitions` interface with the keys of your registry: ```ts // motion.d.ts (anywhere in your app's include path) import type { TransitionConfig } from '@rootnative/inertia' declare module '@rootnative/inertia' { interface RegisteredTransitions { 'state-hover': TransitionConfig 'state-press': TransitionConfig selection: TransitionConfig } } ``` With the augmentation in place, `transition="selectoin"` is a compile error. TypeScript ignores the value type. Only the keys matter. ### Consuming the registry from custom components An adapter package or a custom animated component can support names on its own surface with `useNamedTransitions()` and `resolveNamedTransition()`: ```ts import { resolveNamedTransition, useNamedTransitions, } from '@rootnative/inertia' function useMyAnimatedThing(transition?: TransitionConfig | TransitionName) { const registry = useNamedTransitions() const config = resolveNamedTransition(transition, registry) // config is a concrete TransitionConfig | undefined } ``` ## Reading the resolved value Two hooks let a component react to the active mode: ```tsx import { useMotionConfig, useShouldReduceMotion } from '@rootnative/inertia' function MyComponent() { const { reducedMotion } = useMotionConfig() const reduce = useShouldReduceMotion() // reduce: boolean — already accounts for the OS setting when mode is 'user' } ``` Every Motion primitive uses `useShouldReduceMotion()` internally. In `'user'` mode, it reads the OS setting through the `useReducedMotion()` of Reanimated, which captures the value **once at app start**. A change of the accessibility setting while the app runs takes effect on the next launch, not at once. `'never'` and `'always'` don't consult the OS at all. A change of the `reducedMotion` prop itself re-renders normally. --- # Gestures adapter `@rootnative/inertia-gestures` adds drag, swipe, and pan hooks on `react-native-gesture-handler`. It's an **optional** sibling package. Install it only when you need more than the `pressable` states. The core library doesn't depend on `react-native-gesture-handler`. The hooks compose with any `Motion.*` primitive through a `` and one `style` slot. They don't replace the `gesture` prop. They add what you can do next to it. ## Install ```bash yarn add @rootnative/inertia-gestures react-native-gesture-handler ``` Then follow the [`react-native-gesture-handler` install guide](https://docs.swmansion.com/react-native-gesture-handler/docs/installation). It needs `` near the root of your app. ## `useDrag` Drag a Motion primitive on one or two axes, with optional bounds and an elastic overshoot. ```tsx import { GestureDetector } from 'react-native-gesture-handler' import { Motion } from '@rootnative/inertia' import { useDrag } from '@rootnative/inertia-gestures' function DraggableBox() { const drag = useDrag({ axis: 'both', constraints: { left: -100, right: 100, top: -60, bottom: 60 }, elastic: 0.4, }) return ( ) } ``` | Option | Type | Default | Notes | | ------------- | ---------------------------------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ | | `axis` | `'x' \| 'y' \| 'both'` | `'both'` | Lock the gesture to one axis. | | `constraints` | `{ left?, right?, top?, bottom? }` | none | Bounds in px from the resting position. Each side independently optional. | | `elastic` | `number` (0–1) | `0` | Rubber-band coefficient past `constraints`. `0` hard-clamps; `0.4` is a typical Framer-Motion feel. An overshoot springs back to the bound on release. | | `onDragStart` | `() => void` | none | Fires on JS thread when drag begins. | | `onDragEnd` | `(info: { x, y, velocity: { x, y } }) => void` | none | Fires on JS thread when drag ends. | | `onRelease` | `(info) => ReleaseResult \| void` (worklet) | none | UI-thread release transition — see below. | The hook returns `{ gesture, animatedStyle, dragX, dragY, isDragging }`. The shared values are public for advanced cases, such as a secondary effect that derives from the drag position. **When the bounds change.** A new `constraints` value applies from the next drag. An element at rest outside the new bounds stays there, and it jumps at the first move of the next drag. To move it at once, write `dragX` or `dragY` when you change the bounds. For example, after a rotate changes the width of a slider track, set the thumb to the same fraction of the new track. ### Release transitions (`onRelease`) By default, `useDrag` leaves the shared values where the finger lifted. The one exception is an `elastic` overshoot: an axis that lifted past `constraints` springs back to the nearest bound with the default spring and the release velocity. Pass `onRelease` to animate the values to a settled position with the transition vocabulary of Inertia: a spring snap to a tick, a decay with bounds, a timing settle. The callback runs as a **worklet**, so the release velocity stays on the UI thread with no JS round trip: ```tsx const drag = useDrag({ axis: 'x', constraints: { left: 0, right: trackWidth }, onRelease: (e) => { 'worklet' // Snap to the nearest tick using the release velocity for natural continuation. const snap = nearestTick(e.x, ticks) return { x: { type: 'spring', to: snap, velocity: e.velocity.x }, } }, }) ``` Return one release transition per axis in a `ReleaseResult` shape. Omit an axis, or return nothing, to leave that shared value where it landed, or, after an `elastic` overshoot, to spring it back inside `constraints`. A transition that you return for an axis replaces the spring back on that axis. The transition shapes mirror the core `transition` prop: ```ts type ReleaseTransition = | (SpringTransition & { to: number }) | (TimingTransition & { to: number }) | DecayTransition // no `to` — decay decelerates from current position | (NoAnimationTransition & { to: number }) ``` A decay on release gives a free flick with no snap: ```tsx onRelease: (e) => { 'worklet' return { x: { type: 'decay', velocity: e.velocity.x, clamp: [0, trackWidth] }, } } ``` `onRelease` and `onDragEnd` both fire on release. Use `onRelease` for the shared-value animation. Use `onDragEnd` for JS-thread side effects (analytics, state updates). Internally, the release goes through `buildReleaseAnimation`, which `@rootnative/inertia` exports. It's a worklet-safe builder for a single-step spring, timing, decay, or no-animation transition. Call it directly when you write a custom `Gesture.Pan().onEnd(...)` worklet outside `useDrag`. ## `useSwipe` A directional gesture that commits or snaps back. The hook tracks the live translation while the user drags. On release, it fires `onSwipe` when the distance threshold or the velocity threshold is met along an allowed axis. By default, the position animates back to zero whether the swipe commits or not. That is the correct shape for swipe-to-delete: the row returns, and you remove it. For a card deck, return a commit-exit transition from `onCommit`, so that the committed card continues off screen instead (see below). ```tsx const swipe = useSwipe({ directions: ['left', 'right'], distanceThreshold: 100, onSwipe: (direction) => { if (direction === 'left') dismiss() if (direction === 'right') accept() }, }) return ( {children} ) ``` | Option | Type | Default | Notes | | ------------------- | ------------------------------------------------------ | -------------- | ---------------------------------------------------------------------- | | `directions` | `Array<'left' \| 'right' \| 'up' \| 'down'>` | all four | Only commits along listed directions. Off-axis swipes do nothing. | | `distanceThreshold` | `number` (px) | `80` | Distance past which a release commits. | | `velocityThreshold` | `number` (px/sec) | `800` | Flick velocity that commits even before distance threshold. | | `releaseTransition` | `SnapBackTransition \| TransitionName` | default spring | Transition for the snap-back to zero — see below. | | `onSwipe` | `(direction, { distance, velocity }) => void` | none | JS-thread callback at release. Direction is one of the allowed values. | | `onCommit` | `(direction, info) => ReleaseResult \| void` (worklet) | none | UI-thread commit-exit transition — see below. | | `onSwipeEnd` | `(direction, { finished }) => void` | none | JS-thread callback when a committed swipe's release animation settles. | The dominant axis decides which direction the hook checks. That is the axis where \|tx\| or \|ty\| is larger at release. The hook returns `{ gesture, animatedStyle, swipeX, swipeY, isActive, reset }`. `reset()` snaps both shared values back to zero with no animation. Use it after a commit exit when the next card takes over the same mounted component. A keyed remount gets fresh values and doesn't need it. ### Snap-back transition (`releaseTransition`) The snap-back to zero uses the library default spring. Pass `releaseTransition` to use your own, inline or as a `TransitionName` from the nearest [``](./motion-config#named-transitions). That is how the reset joins a design-token motion system: ```tsx const swipe = useSwipe({ directions: ['left', 'right'], releaseTransition: 'spatial-default', // or { type: 'spring', tension: 220 } onSwipe: (direction) => archive(direction), }) ``` The hook passes the release velocity into a spring for you, unless the config sets `velocity` itself. So a flick that stops short of the threshold resets with the momentum it had, not as if the finger had been still. `SnapBackTransition` is a spring, a timing, or a no-animation transition. A decay is excluded, because the snap-back always targets zero and a decay has no target. A registered name that resolves to a decay config warns in dev and falls back to the default spring. ### Commit exit (`onCommit` + `onSwipeEnd`) The snap-back is correct for swipe-to-delete. A card deck needs the opposite: a **committed** card must continue in the swipe direction and leave the screen. Return one release transition per axis from `onCommit` to run instead of the snap-back. Advance the deck from `onSwipeEnd` when the exit settles: ```tsx const swipe = useSwipe({ directions: ['left', 'right'], onCommit: (direction, info) => { 'worklet' return { x: { type: 'spring', to: direction === 'right' ? 500 : -500, velocity: info.velocity.x, // continue the finger's momentum }, } }, onSwipeEnd: (direction, { finished }) => { if (finished) advanceDeck(direction) }, }) ``` `onCommit` runs as a **worklet** on the UI thread, so write it with the `'worklet'` directive. It fires only when the gesture commits. It receives the same `info` shape as the `onRelease` of `useDrag`: the final translation and the release velocity. The return shape is the same `ReleaseResult`, with one difference: an omitted axis, or a `void` return, snaps back to zero as usual, because zero is the resting state of this hook. `onSwipeEnd` fires on the JS thread when the release animation of the committed swipe settles: the commit exit if one ran, or the snap-back otherwise. That is the moment when the card is gone and the next one takes over. `onSwipe`, which fires at release, can't give you that moment. `finished` is `false` when a new gesture or something else interrupted the animation. `onSwipeEnd` doesn't fire for a release that didn't commit. The order is: `onSwipe` (JS side effects at release), then `onCommit` (the exit decision on the UI thread), then `onSwipeEnd` (JS side effects at settle). Use the subset that the interaction needs. ### `animatedStyle` owns the whole `transform` key `animatedStyle` returns a complete `transform` array. In React Native, `transform` is **one** style key, so a second style with its own `transform` **replaces** this one and doesn't merge with it. A rotation next to it, the first thing that almost every card deck adds, drops the translation with no warning. The card then rotates and doesn't follow the finger: ```tsx // Broken: tiltStyle's transform replaces the swipe translation. ``` A static style next to `animatedStyle` is safe (`[styles.card, swipe.animatedStyle]` above), because a static style declares no `transform`. The conflict appears only when the second style is itself a transform. Build one style from `swipeX` instead of two styles: ```tsx const cardStyle = useInterpolatedStyle(swipe.swipeX, { translateX: [-200, 0, 200], rotate: ['-12deg', '0deg', '12deg'], }) return ( {children} ) ``` A nested second `Motion.View` also works, with one view per transform source, when the transforms come from independent drivers. The same applies to `useDrag` and `usePan`: each one owns its `transform` key too. ## `usePan` A camera-style pan with momentum on release. The position **persists across gestures**: the next pan starts from the current offset, not from zero. On release, the position continues to move with the `withDecay` of Reanimated. ```tsx const pan = usePan({ constraints: { left: -240, right: 240, top: -240, bottom: 240 }, deceleration: 0.997, }) return ( {/* large content */} ) ``` | Option | Type | Default | Notes | | ----------------- | ---------------------------------- | ------------------ | ----------------------------------------------------------------------------- | | `constraints` | `{ left?, right?, top?, bottom? }` | none | Hard clamp during gesture and during decay. | | `deceleration` | `number` | Reanimated default | Higher = momentum dies faster. Roughly `0.99` (slow) to `0.999` (long glide). | | `disableMomentum` | `boolean` | `false` | Hard stop on release (drag-like). | For elastic constraints, use `useDrag({ elastic })`. `usePan` hard-clamps because it uses the `clamp` parameter of `withDecay`, which has no overshoot mode. **When the bounds change.** A new `constraints` value applies from the next pan. An element at rest outside the new bounds stays there, and it jumps at the first move of the next pan. To move it at once, write `panX` or `panY` when you change the bounds. ## When to pick which | Gesture | Snap back on release? | Momentum on release? | Typical UX | | ---------- | --------------------------------------- | ---------------------------- | -------------------------------------------------- | | `useDrag` | No — stays where left | No | Move-to-position, sliders, sortable handles. | | `useSwipe` | Yes — unless `onCommit` returns an exit | No (springs back) | Swipe-to-delete rows, card stacks, dismiss sheets. | | `usePan` | No — stays where left | Yes — coasts via `withDecay` | Maps, zoomable canvases, large-image navigation. | ## Scope: touch + mouse only All three hooks use `react-native-gesture-handler`, which reports touch and mouse events but **not keyboard** events. Some controls need keyboard accessibility next to drag: a Slider with arrow-key steps, a scrollbar with `PageUp` and `PageDown`, a range input. For those, use [`useTouchDrag`](./api/hooks#usetouchdragoptions) from `@rootnative/inertia/touch` instead. It's the PanResponder counterpart of `useDrag`. It's part of core, needs no `react-native-gesture-handler` peer, and composes with `onKeyDown` on the wrapping `View`. `onKeyDown` fires on web. For iOS and Android, see the [keyboard note](./api/hooks#usetouchdragoptions). The full ladder: 1. `Motion.View` with the `gesture` prop: state-overlay UX only (hover, focus, press). 2. `useTouchDrag` from `@rootnative/inertia/touch`: a pointer drag that composes with key events, with no extra peer dependency. 3. `useDrag`, `useSwipe`, and `usePan` from this package: pointer only, on gesture-handler. Best for a project that already uses gesture-handler. The UI-thread release path is more precise than the JS-thread velocity of PanResponder. 4. Raw `PanResponder` with `useAnimation`: use this when the gesture lifecycle itself needs custom code (multi-touch composition, a custom capture predicate beyond the axis lock). `useTouchDrag` and the gesture-handler `useDrag` accept the same `onRelease` shape, and both go through `buildReleaseAnimation`. So a swap between them changes only the wiring, not the release animation config. ## Why a separate package? The `gesture` prop of the core library covers `pressed`, `focused`, `focusVisible`, and `hovered`: boolean state-overlay gestures with no continuous translation. Drag, swipe, and pan are **value-driven**. The gesture publishes a continuous position, and you compose it into the style of the view. These gestures don't fit the boolean-state model, and they need `react-native-gesture-handler`, which we don't want as a required peer of core. A separate package keeps the surface of core small and keeps the gesture-handler dependency opt-in. The hooks return primitives (`gesture`, `animatedStyle`, shared values) and don't wrap Motion in a new component, so they work with the existing `Motion.*` set. --- # Gradients `@rootnative/inertia-gradients` adds an animatable linear gradient built on `expo-linear-gradient`. It's an **optional** sibling package. Install it only when you need to animate gradient stops. The core library doesn't depend on `expo-linear-gradient`. `MotionLinearGradient` accepts the same `initial`, `animate`, and `transition` shape as the core `Motion.*` primitives, with the animatable keys `colors`, `start`, `end`, and `locations`. ## When to pick which | You want | Reach for | | ----------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- | | Animate a **flat** background color | `Motion.View` with `animate={{ backgroundColor }}` from core — no gradient package needed | | Animate gradient stop colors, direction, or stop positions | `MotionLinearGradient` (this package) | | Change the **number** of stops | A remount via `key={...}` — the slot count is locked at mount | | A radial or conic gradient | Not covered — linear only; radial / conic are backlog, unscheduled | | A gradient fill inside an SVG | `` + `` from `react-native-svg`, referenced by `url(#id)` — see the [SVG page](./svg.mdx) | ## Install ```bash yarn add @rootnative/inertia-gradients expo-linear-gradient ``` `expo-linear-gradient` works in a bare React Native project and in Expo, but it's an Expo Module. A bare project needs the Expo modules runtime. See [Installing Expo modules](https://docs.expo.dev/bare/installing-expo-modules/). ## Usage ```tsx import { MotionLinearGradient } from '@rootnative/inertia-gradients' function Hero() { return ( ) } ``` The static `colors` prop is required. It sets the visual on the first render and **locks the slot count** for the lifetime of the component. To resize the gradient (for example, from 2 stops to 3 stops), remount it with `key={...}`. The component throws in dev if `colors.length` changes between renders. ## Animatable props | Key | Shape | Notes | | ----------- | -------------------------- | ----------------------------------------------------------------------------------------------------------------------------- | | `colors` | `readonly string[]` | Element-wise color interpolation via Reanimated's color setter. Length must match the static `colors` prop. | | `start` | `{ x: number, y: number }` | Normalized `[0, 1]` coordinates. `x` and `y` animate independently — useful for rotating gradient direction. | | `end` | `{ x: number, y: number }` | Same shape as `start`. | | `locations` | `readonly number[]` | Optional stop positions. If supplied at mount, must remain supplied and same-length as `colors` for the component's lifetime. | Per-property transitions work the same as in the core primitives: ```tsx ``` ## `initial` Pass `initial` to override the values of the mount frame, so the component starts somewhere other than the static props. Pass `initial={false}` to start at the `animate` target with no mount animation. ```tsx ``` ## Reduced motion `MotionLinearGradient` follows [``](./motion-config.md) the same as the core primitives. When the reduce-motion setting of the OS is on, or you pass `reducedMotion="always"`, a transition resolves as a direct assignment instead of `withSpring` or `withTiming`. ## What this primitive doesn't do - **Radial or conic gradients.** The primitive is linear only. Radial and conic are in the backlog, not scheduled. They need their own prop shape, and the linear API must prove itself first. - **A slot-count resize.** The length of the colors array is locked at mount. To change it, remount with `key={...}`. - **Sequence keyframes per stop.** `animate.colors` accepts one target array, not a nested array of arrays. For chained gradient transitions, drive the target through state and let React re-render. --- # SVG `@rootnative/inertia-svg` adds animatable SVG primitives built on [`react-native-svg`](https://github.com/software-mansion/react-native-svg). It's an **optional** sibling package. Install it only when you need to morph a path or animate `fill` or `stroke`. The core library doesn't depend on `react-native-svg`. `MotionPath` wraps ``. It accepts the same `initial`, `animate`, and `transition` shape as the core `Motion.*` primitives, with animatable keys for the path data (`d`) and for the color and numeric paint properties. The prebuilt [`MotionCircle`, `MotionRect`, and `MotionLine`](#shapes) cover the other common shapes. The [`createMotionSvgComponent`](#factory) factory behind them wraps any `react-native-svg` element. ## When to pick which | You want | Reach for | | ----------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------- | | Morph one shape into another (same command sequence) | `MotionPath` with `animate.d` — see [structural compatibility](#structural-compatibility) | | Switch between structurally **different** shapes | A remount via `key={...}`, not a morph | | Animate a circle / rect / line's geometry or paint | [`MotionCircle` / `MotionRect` / `MotionLine`](#shapes) | | A "draw the stroke" effect (progress ring, signature) | Animate `strokeDashoffset` against a static `strokeDasharray` — see the [progress-ring example](#shapes) | | Animate any other `react-native-svg` element (`Ellipse`, …) | [`createMotionSvgComponent`](#factory) | | A gradient fill inside the SVG | `` + `` from `react-native-svg`; the path references it by `url(#id)` — not this package | | Animate a non-SVG view | The core `Motion.*` primitives — this package is for `react-native-svg` elements only | ## Install ```bash yarn add @rootnative/inertia-svg react-native-svg ``` `react-native-svg` works in a bare React Native project and in Expo. ## Usage ```tsx import Svg from 'react-native-svg' import { MotionPath } from '@rootnative/inertia-svg' function Toggle({ open }) { return ( ) } ``` The package also exports a `MotionSvg` namespace, which groups the components for autocomplete. `MotionSvg.Path` and `MotionPath` are the same component, so pick the import style that matches your codebase: ```tsx import { MotionSvg } from '@rootnative/inertia-svg' ; ``` The namespace also carries the prebuilt shapes: `MotionSvg.Circle`, `MotionSvg.Rect`, and `MotionSvg.Line`. See [Shapes](#shapes) below. The static `d` prop is required. Its **command sequence is locked at the first render**. Every target `d` that you pass in `animate` or `initial` must give the same command letters in the same order after implicit-repeat expansion. Element-wise scalar interpolation is the whole morphing model. ## Structural compatibility Two paths can morph only when their normalized templates (the command letters, in order, with the case kept) are equal. Examples: ``` ✅ M 0 0 L 10 10 Z ↔ M 50 50 L 80 80 Z same: M L Z ✅ M 0 0 L 10 10 L 20 20 ↔ M 0 0 50 50 60 60 same: M L L (implicit repeats after M expand to L) ❌ M 0 0 L 10 10 Z ↔ M 0 0 L 10 10 differs: count ❌ M 0 0 L 10 10 ↔ M 0 0 l 10 10 differs: absolute L vs relative l ❌ M 0 0 L 10 10 ↔ M 0 0 C 1 1 2 2 3 3 differs: L vs C ``` The component throws in dev when the templates differ: at mount (if `initial.d` doesn't match the static `d`), when `animate.d` changes its shape, or when the static `d` prop itself changes its shape between renders. In production, the component skips the bad target instead. The path keeps its current `d`, and a mismatched `initial.d` falls back to the static `d`, so one bad value doesn't crash the screen. Treat a dev error as a defect. To switch between shapes with a different structure, **remount with a new `key`**: ```tsx ``` Path normalization that resamples between arbitrary shapes (the approach of flubber) is out of scope by design. ## Animatable props | Key | Shape | Notes | | ------------------ | -------- | --------------------------------------------------------------------------------------------------------------------------- | | `d` | `string` | Path data. Source and target must share the same template — see above. Each scalar param springs / times independently. | | `fill` | `string` | Color, interpolated via Reanimated's color setter. Defaults to `TRANSPARENT` (`rgba(0, 0, 0, 0)`) if neither static nor `initial` is supplied. The SVG keyword `none` maps to `TRANSPARENT`, because Reanimated's color processor rejects it. | | `stroke` | `string` | Same as `fill`. | | `strokeWidth` | `number` | Numeric. Default seed `1`. | | `strokeOpacity` | `number` | Numeric, 0–1. | | `fillOpacity` | `number` | Numeric, 0–1. | | `opacity` | `number` | Numeric, 0–1. | | `strokeDashoffset` | `number` | Useful for "draw" animations on a dashed stroke. | Per-property transitions work the same as in the core primitives: ```tsx ``` ## `initial` Pass `initial` to override the values of the mount frame, so the component starts somewhere other than the static props. Pass `initial={false}` to start at the `animate` target with no mount animation. ```tsx ``` If you pass `initial.d`, its template must match the static `d`, the same rule as for `animate.d`. ## Reduced motion `MotionPath` follows [``](./motion-config.md) the same as the core primitives. When the reduce-motion setting of the OS is on, or you pass `reducedMotion="always"`, a transition resolves as a direct assignment instead of `withSpring` or `withTiming`. ## Shapes — MotionCircle, MotionRect, MotionLine {#shapes} Prebuilt animatable wrappers for the common shapes that aren't paths, built with the [factory](#factory) below. Each one accepts the same `initial`, `animate`, and `transition` shape as `MotionPath`. `transition` also accepts a [named transition](./motion-config.md#named-transitions) from the nearest ``, top-level and per property. | Component | Numeric props | Color props | Array props | | -------------- | --------------------------------------------------------------------------------------------------------------------- | ---------------- | ----------------- | | `MotionCircle` | `cx`, `cy`, `r`, `strokeWidth`, `strokeOpacity`, `fillOpacity`, `opacity`, `strokeDashoffset` | `fill`, `stroke` | `strokeDasharray` | | `MotionRect` | `x`, `y`, `width`, `height`, `rx`, `ry`, `strokeWidth`, `strokeOpacity`, `fillOpacity`, `opacity`, `strokeDashoffset` | `fill`, `stroke` | `strokeDasharray` | | `MotionLine` | `x1`, `y1`, `x2`, `y2`, `strokeWidth`, `strokeOpacity`, `opacity`, `strokeDashoffset` | `stroke` | `strokeDasharray` | The canonical use of `MotionCircle` is a circular progress ring: a static `strokeDasharray` of the circumference with an animated `strokeDashoffset`: ```tsx import Svg from 'react-native-svg' import { MotionCircle } from '@rootnative/inertia-svg' const CIRCUMFERENCE = 2 * Math.PI * 45 function ProgressRing({ progress }: { progress: number }) { return ( ) } ``` The rules for the shapes mirror the command-sequence lock of `MotionPath`: - **An array prop locks its length at the first render.** `strokeDasharray` interpolates element-wise, so a target with a different length throws in dev, and production ignores it. Remount with a new `key` to change the length. - **A key animates only when it's present at mount**, in the static props, in `initial`, or in `animate`. A key that enters `animate` after mount warns in dev, and the component ignores it. A key that nothing names passes through as an ordinary static prop, so an attribute that you don't animate keeps its element default. - **`fill="none"` and `stroke="none"` are safe.** A static `none` with no `initial` and no `animate` for that key stays a static prop. A `none` in `initial` or in `animate` maps to `TRANSPARENT`, which paints the same nothing. The color processor of Reanimated rejects the keyword, so the adapter never sends it through `animatedProps`. - A numeric key that only `animate` names seeds from `0`. A color seeds from `TRANSPARENT` (`rgba(0, 0, 0, 0)`, exported from `@rootnative/inertia`). Give the key a static prop or an `initial` value when the mount animation must start elsewhere. ## createMotionSvgComponent {#factory} The factory behind the prebuilt shapes. Point it at any `react-native-svg` element, and declare which props animate and how each one interpolates: ```tsx import { Ellipse } from 'react-native-svg' import { createMotionSvgComponent } from '@rootnative/inertia-svg' const MotionEllipse = createMotionSvgComponent(Ellipse, { animatableProps: ['cx', 'cy', 'rx', 'ry', 'opacity'], // numeric colorProps: ['fill', 'stroke'], // color strings arrayProps: ['strokeDasharray'], // numeric arrays, length locked at mount }) ``` TypeScript infers the prop keys from the wrapped component, so a typo in `animatableProps` is a compile error, and the `animate` and `initial` of the generated component accept only the declared keys. Everything above about the shapes (named transitions, per-property transitions, the `initial` rules, reduced motion, the mount locks) comes from the factory and applies to any component that it builds. `MotionPath` stays hand-written, because path morphing needs the `d` template machinery that the generic factory doesn't model. ## What this package doesn't do - **Path resampling** between shapes with a different structure. Only a morph with the same template works. For the rest, remount with `key`. - **A gradient fill inside the SVG.** For a gradient fill, use `` and `` from `react-native-svg`, and animate the stops with the patterns of [`MotionLinearGradient`](./gradients.mdx). The path only references the gradient by `url(#id)`. - **Path command interpolation** (for example, a morph from an `L` to a `C`). Element-wise scalar interpolation is intentional. It's predictable, cheap, and matches what designers want 95% of the time. ## Path utilities The package exports the tokenizer and the template helpers for downstream tooling: ```ts import { parsePathD, templateOf, diffTemplate, flattenParams, serializePath, } from '@rootnative/inertia-svg' const segs = parsePathD('M 0 0 L 10 10 Z') // [{ cmd: 'M', args: [0, 0] }, …] const t = templateOf(segs) // { cmds: ['M','L','Z'], widths: [2,2,0], size: 4 } const params = flattenParams(segs) // [0, 0, 10, 10] const out = serializePath(t, [5, 5, 20, 20]) // 'M 5 5L 20 20Z' const err = diffTemplate(t, templateOf(parsePathD('M 0 0 L 1 1'))) // → 'command count differs: …' ``` `serializePath` is a worklet. Call it inside `useAnimatedProps` when you build your own SVG primitives on this layer. --- # Static export & SSR A static export renders your tree on a server and writes the result into HTML. `Motion.*` renders at its `initial` values, so an element that animates in from `opacity: 0` ships as: ```html
…
``` That is correct while the bundle loads and takes over. It's a **blank page** for a visitor whose bundle fails, whose connection drops it, or who blocks scripts. :::warning No automated check sees this failure The build succeeds. The HTML is valid. The page is perfect in development, where the bundle always runs. Nothing errors, nothing warns, and no test fails. The content is gone for a visitor with no JavaScript. Only a human who loads the page with scripts off sees it. ::: ## The fix: one style block Add this to your HTML shell. For Expo Router that is `app/+html.tsx`. ```tsx title="app/+html.tsx" import { entranceGuardCss, entranceGuardNoscriptCss, } from '@rootnative/inertia/static-export' import type { PropsWithChildren } from 'react' export default function Root({ children }: PropsWithChildren) { return (