react-spring Documentation

️ A spring physics based React animation library

29,138 stars TypeScript TypeScript 1 file · ~13,169 tokens #animation-library#react#react-spring#spring-physics#springs
RAW Doc

Docker & Self-Hosted Deployment Verified OCI

Deploy react-spring on any server, homelab, or cloud container platform.

1-Click Terminal Command
bash (docker run)
docker run -d --name react-spring -p 8080:8080 --restart always pmndrs/react-spring:latest

1. Project Overview & Quickstart (pmndrs/react-spring)

File: README.md

react-spring

A spring-physics first animation library giving you flexible tools to confidently cast your ideas

react-spring is a cross-platform spring-physics first animation library.

It's as simple as:

jsx
const styles = useSpring({
  from: {
    opacity: 0
  },
  to: {
    opacity: 1
  }
})

<animated.div style={styles} />

Just a small bit about us:

  • Cross-Platform: We support react-dom and react-three-fiber.
  • Versatile: Be declarative with your animations or if you prefer, imperative.
  • Spring-Physics First: By default animation use springs for fluid interactivity, but we support durations with easings as well.

There's a lot more to be had! Give it a try and find out.

Getting Started

⚡️ Jump Start

shell
# Install the target you need
npm install @react-spring/web
# or, for react-three-fiber
npm install @react-spring/three
jsx
import { animated, useSpring } from '@react-spring/web'

const FadeIn = ({ isVisible, children }) => {
  const styles = useSpring({
    opacity: isVisible ? 1 : 0,
    y: isVisible ? 0 : 24,
  })

  return <animated.div style={styles}>{children}</animated.div>
}

It's as simple as that to create scroll-in animations when value of isVisible is toggled.

📖 Documentation and Examples

More documentation on the project can be found here.

Pages contain their own examples which you can check out there, or open in codesandbox for a more in-depth view!


📣 What others say

Used by



And many others...

Backers

Thank you to all our backers! 🙏 If you want to join them here, then consider contributing to our Opencollective.

Contributors

This project exists thanks to all the people who contribute.


File: docs/app/routes/docs._index.mdx


meta: title: Overview | React Spring 'og:title': Overview | React Spring 'twitter:title': Overview | React Spring 'description': Documentation overview for React Spring. 'og:description': Documentation overview for React Spring. 'twitter:description': Documentation overview for React Spring. 'og:url': https://www.react-spring.dev/docs 'twitter:url': https://www.react-spring.dev/docs sidebar_position: 1 noSubnav: true

import { formatFrontmatterToRemixMeta } from '../helpers/meta'

export const meta = formatFrontmatterToRemixMeta(frontmatter)

Overview

Welcome to the react-spring docs site!

import { NAV_TILES } from '../data/fixtures'
import { NavigationGrid } from '../components/Grids/NavigationGrid'

What is this?

Our old documentation was lacking in features & clarity. So, based on
community feedback, we've made an endeavor to improve our documentation with a
few key differences:

  • We want to explain more of our codebase conceptually e.g what is an animated
    component
  • All our content will be searchable so no more running around in the dark
  • Step-by-step tutorials on how to achieve common use-cases

How can I help?

Thank you for being interested in helping! It means a lot, if you want to provide
generic feedback please do so here.
Otherwise, each page has it's own feedback button you can use to give an up or down
vote, followed by the option to then add written feedback.

If you're interested in adding an example to the site then why not check out the specific
contributing guide.


File: docs/app/routes/docs.advanced._index.mdx


meta: title: Advanced API | React Spring sidebar_position: 5 noPage: true


File: docs/app/routes/docs.advanced.async-animations.mdx


meta: title: Async Animations | React Spring 'og:title': Async Animations | React Spring 'twitter:title': Async Animations | React Spring 'og:description': An advanced guide to Async Animations and what they are in React Spring. 'twitter:description': An advanced guide to Async Animations and what they are in React Spring. 'og:url': https://www.react-spring.dev/docs/advanced/async-animations 'twitter:url': https://www.react-spring.dev/docs/advanced/async-animations sidebar_position: 7

import { formatFrontmatterToRemixMeta } from '../helpers/meta'

export const meta = formatFrontmatterToRemixMeta(frontmatter)

Async Animations

:::note
This is an advanced guide. If you're new to react-spring, you should start with the getting started page
and become familar with the library before jumping into async animations.
:::

Aren't all animations async?

Well technically in react-spring yes, you could consider animations to be async? The start function of a Controller is async and therefore
the imperative api is too, async. And then your styles are updated asynchronously... But that's not what this guide is referring too.

When we talk about async animations we refer to the ability to perform X amount of transformations with only one call of the APIs and each
animation chunk will finish before the other begins. If you look at the example below, this animation has only a config object, loop prop
and a to prop.

tsx live=true showcode=false
import { useSpring, animated } from '@react-spring/web'

export default function MyComponent() {
  const springs = useSpring({
    from: { background: '#ff6d6d', y: -40, x: 0 },
    to: [
      { x: 80, background: '#fff59a' },
      { y: 40, background: '#88DFAB' },
      { x: 0, background: '#569AFF' },
      { y: -40, background: '#ff6d6d' },
    ],
    loop: true,
  })

  return (
    <animated.div
      style={{
        width: 40,
        height: 40,
        borderRadius: 4,
        ...springs,
      }}
    />
  )
}

The `to` prop

If you've read any of the component pages, you'll know we accept a to prop, it's typically used as an object,
but alternatively, you can also use an array (chaining the animations) or a function (writing an animation script).

When you consider the options you have as to what you can pass to the to prop, you'll begin to understand how complicated
your animations can be, it's then a matter of understand what you're trying to achieve and applying the best solution.

Chaining animations

The array syntax is a middleground between total control of async animations and the simplicity of passing just an object.
Just like the start method of the imperative api, you don't need to reference every key for each update. Each update will fire
when the previous one has finished.

tsx lines=6-11 live=true defaultopen=true
import { useSpring, animated } from '@react-spring/web'

export default function MyComponent() {
  const springs = useSpring({
    from: { background: '#ff6d6d', y: -40, x: 0 },
    to: [
      { x: 80, background: '#fff59a' },
      { y: 40, background: '#88DFAB' },
      { x: 0, background: '#569AFF' },
      { y: -40, background: '#ff6d6d' },
    ],
    loop: true,
  })

  return (
    <animated.div
      style={{
        width: 40,
        height: 40,
        borderRadius: 4,
        ...springs,
      }}
    />
  )
}

Writing animation scripts

When you need most control of your animation, it's best to write a script by providing a function to the to prop.
The function receives two arguments, the next function which accepts an object of updates, again similar to the start
method of the imperative API and a cancel function which works the same as the stop method of the imperative API.

This therefore allows you to cancel scripts at any time meaning you can react to external events & conditions.

For further reading, see imperative API.

tsx lines=6-11 live=true defaultopen=true
import { useSpring, animated } from '@react-spring/web'

export default function MyComponent() {
  const springs = useSpring({
    from: { background: '#ff6d6d', y: -40, x: 0 },
    to: async (next, cancel) => {
      await next({ x: 80, background: '#fff59a' })
      await next({ y: 40, background: '#88DFAB' })
      await next({ x: 0, background: '#569AFF' })
      await next({ y: -40, background: '#ff6d6d' })
    },
    loop: true,
  })

  return (
    <animated.div
      style={{
        width: 40,
        height: 40,
        borderRadius: 4,
        ...springs,
      }}
    />
  )
}

File: docs/app/routes/docs.advanced.config.mdx


meta: title: Spring Configs | React Spring 'og:title': Spring Configs | React Spring 'twitter:title': Spring Configs | React Spring 'og:description': An advanced guide to the configs of Controllers, Components & SpringValues in React Spring. 'twitter:description': An advanced guide to the configs of Controllers, Components & SpringValues in React Spring. 'og:url': https://www.react-spring.dev/docs/advanced/config 'twitter:url': https://www.react-spring.dev/docs/advanced/config sidebar_position: 1

import { formatFrontmatterToRemixMeta } from '../helpers/meta'

export const meta = formatFrontmatterToRemixMeta(frontmatter)

Spring Configs

Part of a component's configuration argument, the config prop is an object
with many properties that can be used to customize & fine tune your animations.
It directly controls how your springs behave and can customized on a spring by
spring basis (e.g. opacity and scale could be different for one useSpring hook).

Usage

Basic Usage

Your most typical usage of the config prop is to edit the mass, friction and tension properties.

jsx lines=7-11
import { useSpring, animated } from '@react-spring/web'

const MyComponent = () => {
  const [springs, api] = useSpring(
    () => ({
      y: 0,
      config: {
        mass: 5,
        friction: 120,
        tension: 120,
      },
    }),
    []
  )

  return <animated.div style={springs} />
}

Config per SpringValue

The config prop can also be a function where the argument is the key of the
spring value, this is great if you want one spring to control many elements or
have properties behave in different ways like a smooth opacity change but a
bouncy scale.

jsx lines=8-18
import { useSpring, animated } from '@react-spring/web'

const MyComponent = () => {
  const [springs, api] = useSpring(
    () => ({
      backgroundColor: '#00ff00',
      y: 0,
      config: key => {
        if (key === 'y') {
          return {
            mass: 5,
            friction: 120,
            tension: 120,
          }
        }

        return {}
      },
    }),
    []
  )

  return <animated.div style={springs} />
}

Returning an empty object will enforce the default config options:
{ mass: 1, tension: 170, friction: 26 }.

Partial Updates

When using the spring api you can partially update your configs.
These partial configs are merged with the original config for each
call of the api.

jsx lines=17-22
import { useSpring, animated } from '@react-spring/web'

const MyComponent = () => {
  const [springs, api] = useSpring(
    () => ({
      y: 0,
      config: {
        mass: 5,
        friction: 120,
        tension: 120,
      },
    }),
    []
  )

  const handleClick = () => {
    api.start({
      y: 20,
      config: {
        friction: 10,
      },
    })
  }

  return <animated.div onClick={handleClick} style={springs} />
}

Presets

Additionally to being able to configure your own spring, we export a
small selection of presets enclosed in the config named export.

jsx
import { config } from '@react-spring/web'

The presets are:

import { DescriptiveList } from '../components/Text/List'

<DescriptiveList
data={[
['default', {{ tension: 170, friction: 26 }}],
['gentle', {{ tension: 120, friction: 14 }}],
['wobbly', {{ tension: 180, friction: 12 }}],
['stiff', {{ tension: 210, friction: 20 }}],
['slow', {{ tension: 280, friction: 60 }}],
['molasses', {{ tension: 280, friction: 120 }}],
]}
/>

Config Visualizer

jsx live=true template=configplayground showcode=false
import { useRef, useState } from 'react'
import { useSpring, animated } from '@react-spring/web'
import { useControls } from 'leva'

export default function Card() {
  const cardRef = useRef(null)
  const config = useControls({
    mass: 1,
    tension: 170,
    friction: 26,
    clamp: false,
    precision: 0.01,
    velocity: 0,
  })

  const [{ xys }, api] = useSpring(() => ({ xys: [0, 0, 1], config }), [config])

  const handleMouseLeave = () =>
    api.start({
      xys: [0, 0, 1],
    })

  const handleMouseMove = e => {
    const rect = cardRef.current.getBoundingClientRect()
    api.start({
      xys: calc(e.clientX, e.clientY, rect),
    })
  }

  return (
    
      <animated.div
        className="card"
        style={{ transform: xys.to(trans) }}
        onMouseLeave={handleMouseLeave}
        onMouseMove={handleMouseMove}
      />
    
  )
}

const calc = (x, y, rect) => [
  -(y - rect.top - rect.height / 2) / 5,
  (x - rect.left - rect.width / 2) / 5,
  1.4,
]

const trans = (x, y, s) =>
  `perspective(600px) rotateX(${x}deg) rotateY(${y}deg) scale(${s})`

Easings

Easings can only be used in conjunction with the duration property.

Why Springs?

We think of animation in terms of time and curves, but that causes most of the struggle we face
when trying to make elements on the screen move naturally, because nothing in the real world
moves like that. Springs don’t have a defined curve or a set duration.

As Andy Matuschak (ex Apple UI-Kit developer) expressed – “Animation APIs parameterized by duration
and curve are fundamentally opposed to continuous, fluid interactivity.”

Available generic easings

All the following easings are part of the easings object imported like so:

jsx
import { easings } from '@react-spring/web'

import { TableGeneric } from '../components/Tables/TablesConfig'
import { easingData } from '../data/fixtures'

Steps easing

This unique easing function returns the standard EasingFunction a config object expects. Its still part
of the easings object but you need to set it up before passing.

jsx
import { easings } from '@react-spring/web'

const MyComponent = () => {
  const [springs, api] = useSpring(
    () => ({
      y: 0,
      config: {
        easing: easings.steps(5),
      },
    }),
    []
  )

  return <animated.div style={springs} />
}

It can also take a Direction as a second argument, which can be either start or end. The signature
for the function is shown below:

ts
export function steps(
  steps: number,
  direction: Direction = 'end'
): EasingFunction

Reference

import { TablesConfiguration } from '../components/Tables/TablesConfig'
import { configData } from '../data/fixtures'

Pitfalls

My animation jumps at the end.

In some instances such as animating threejs the items can feel as if they skip the
last couple of frames. This is because the precision prop has a default value of 0.01.
Try editing this value to be 0.0001 to resolve this.

My animation is bouncing and I just want it to stop.

Sometimes you want a snapping feel so you create a sharp spring. When you animate the spring
the animation bounces around, this is because of the physics. An easy solution to this is to
set clamp to true. Your spring will stop animating at the point it hit's it's goal value.


File: docs/app/routes/docs.advanced.controller.mdx


meta: title: Controller | React Spring 'og:title': Controller | React Spring 'twitter:title': Controller | React Spring 'og:description': An advanced API guide to the Controller class in React Spring. 'twitter:description': An advanced API guide to the Controller class in React Spring. 'og:url': https://www.react-spring.dev/docs/advanced/controller 'twitter:url': https://www.react-spring.dev/docs/advanced/controller sidebar_position: 3

import { formatFrontmatterToRemixMeta } from '../helpers/meta'

export const meta = formatFrontmatterToRemixMeta(frontmatter)

Controller

Manages SpringValues for our spring hooks.

Usage

Basic usage, the Controller class you initialise can be used as an imperative api
to control your SpringValues. Meanwhile you pass Controller.springs to your animated component.

tsx
import { Component, createRef } from 'react'
import { Controller, animated } from '@react-spring/web'

class AnimatedComponent extends Component {
  isShowing = createRef(false)
  animations = new Controller({ opacity: 0 })

  toggle = () => {
    this.animations.start({ opacity: this.isShowing ? 1 : 0 })

    this.isShowing = !this.isShowing
  }

  render() {
    return (
      <>
        click
        <animated.div style={this.animations.springs}>I will fade</animated.div>
      </>
    )
  }
}

Constructor Arguments

Below is the arguments that can passed to the constructor of the Controller class.

ts
const ControllerProps = {
  ref,
  from,
  loop,
  onStart,
  onRest,
  onChange,
  onPause,
  onResume,
  onProps,
  onResolve,
}

Properties

import { TablesConfiguration } from '../components/Tables/TablesConfig'
import { CONTROLLER_PROPERTIES_DATA } from '../data/fixtures'

Methods

Get

Gets the current values of our springs.

ts
get(): State & UnknownProps;

Set

Set the current values without animating.

ts
set(values: Partial<State>): void;

Update

Push an update onto the queue of each value.

ts
update(props: ControllerUpdate<State> | Falsy): this;

Start

Start the queued animations for every spring, and resolve the returned promise once all queued
animations have finished or been cancelled. When you pass a queue (instead of nothing), that
queue is used instead of the queued animations added with the update method, which are left alone.

ts
start(props?: OneOrMore<ControllerUpdate<State>> | null): AsyncResult;

Stop

Stop all queued animations for every spring at the same time, or alternatively provide a selection
of keys that should be stopped.

ts
stop(): this;
stop(keys: OneOrMore<string>): this;
stop(cancel: boolean): this;
stop(cancel: boolean, keys: OneOrMore<string>): this;
stop(keys?: OneOrMore<string>): this;
stop(cancel: boolean, keys?: OneOrMore<string>): this;

Pause

Freeze the active animation in time.

ts
pause(keys?: OneOrMore<string>): this;

Resume

Resume the animation if paused.

ts
resume(keys?: OneOrMore<string>): this;

Each

Call a function once per spring value.

ts
each(iterator: (spring: SpringValue, key: string) => void): void

File: docs/app/routes/docs.advanced.events.mdx


meta: title: Events | React Spring 'og:title': Events | React Spring 'twitter:title': Events | React Spring 'og:description': An advanced guide to the event system of Controllers, Components & SpringValues in React Spring. 'twitter:description': An advanced guide to the event system of Controllers, Components & SpringValues in React Spring. 'og:url': https://www.react-spring.dev/docs/advanced/events 'twitter:url': https://www.react-spring.dev/docs/advanced/events sidebar_position: 2

import { formatFrontmatterToRemixMeta } from '../helpers/meta'

export const meta = formatFrontmatterToRemixMeta(frontmatter)

Events

There are a handful of events you can use to react to the state of animation at certain points in time.

Keys vs Springs

Every event function can either be a function on it's own or be an object to which it's keys correlate
to the keys of the spring:

jsx line=5-6,15-19
useSpring(
  () => ({
    x: 0,
    y: 0,
    // onStart is called when the animation of the spring starts
    onStart: () => console.log('the spring has started'),
  }),
  []
)

useSpring(
  () => ({
    x: 0,
    y: 0,
    onStart: {
      // onStart is called for each key when the animation starts
      x: () => console.log('x key has started'),
      y: () => console.log('y key has started'),
    },
  }),
  []
)

The latter form can be useful if for example you have different configs for different keys.
Or you want to do different events based on different keys, e.g. you want to imperatively
update an objects rotation based on the x key.

onStart

Called when the animation begins.

:::warning
onStart is called after the first animation tick, this value is therefore considered dirty.
:::

ts
type OnStart = (
  result: AnimationResult,
  spring: Controller | SpringValue,
  item?: Item
) => void

onChange

Called on every frame.

ts
type OnChange = (
  result: AnimationResult,
  spring: Controller | SpringValue,
  item?: Item
) => void

onRest

Called when the animation comes to a stand-still.

ts
type OnRest = (
  result: AnimationResult,
  spring: Controller | SpringValue,
  item?: Item
) => void

onPause

Called when the animation is paused.

ts
type OnPause = (
  result: AnimationResult,
  spring: Controller | SpringValue,
  item?: Item
) => void

onResume

Called when the animation is resumed.

ts
type OnResume = (
  result: AnimationResult,
  spring: Controller | SpringValue,
  item?: Item
) => void

onResolve

Called when the promise for the update is resolved.

ts
type OnResolve = (
  result: AnimationResult,
  spring: Controller | SpringValue,
  item?: Item
) => void

onProps

Called after an animation is updated by new props, even if the animation remains idle.

ts
type OnProps = (
  props: {[key: string]: any}
  spring: SpringValue,
) => void

onDestroyed

Called after a transition item is unmounted.

ts
type OnDestroyed = (
  item: Item
  key: string | number
) => void

Typescript

ts
interface AnimationResult {
    // Type inference will solve this for you.
    value: SpringValue | { [keyof SpringValues]: number} | number
    finished: boolean
    cancelled: boolean
}

A note on `Item`

The Item argument is only present when using the relevant events within the useTransition hook.


File: docs/app/routes/docs.advanced.interpolation.mdx


meta: title: Interpolation | React Spring 'og:title': Interpolation | React Spring 'twitter:title': Interpolation | React Spring 'og:description': An advanced guide to the interpolation API in React Spring. 'twitter:description': An advanced guide to the interpolation API in React Spring. 'og:url': https://www.react-spring.dev/docs/advanced/interpolation 'twitter:url': https://www.react-spring.dev/docs/advanced/interpolation sidebar_position: 6

import { formatFrontmatterToRemixMeta } from '../helpers/meta'

export const meta = formatFrontmatterToRemixMeta(frontmatter)

Interpolation

What is one?

An interpolation typically is a function that takes a value returns another value. You can even map ranges
of values – numbers are typically required as the input range. So for example, if you want to animate a value
from 0 to 100, you can use an interpolation to map the range 0 to 1 to 0 to 100.

Basic Usage

Extending the `SpringValue`

The most common use of our interpolation is to convert the value of a SpringValue to another value. This is
done by using the to method.

tsx lines=10
import { useSpring, animated } from '@react-spring/web'

function MyComponent() {
  const props = useSpring({
    from: { x: 0 },
    to: { x: 360 },
  })

  return (
    <animated.div
      style={{ transform: props.x.to(value => `rotateZ(${value}deg)`) }}
    >
      Hello World
    </animated.div>
  )
}

Using the `to` function

Similar to the example above, it's also possible to use our to function to convert SpringValues.

tsx lines=1,10
import { useSpring, animated, to } from '@react-spring/web'

function MyComponent() {
  const props = useSpring({
    from: { x: 0 },
    to: { x: 360 },
  })

  return (
    <animated.div
      style={{ transform: to(props.x, value => `rotateZ(${value}deg)`) }}
    >
      Hello World
    </animated.div>
  )
}

Advanced Usage

Combining values

A more advanced use of our interpolation is to combine multiple SpringValues. This normally requires the
use of our to function to create.

tsx lines=1,10
import { animated, to, useSpring } from '@react-spring/web'

export default function MyComponent() {
  const props = useSpring({
    from: { x: 0, y: 0, z: 0 },
    to: { x: 1, y: 1, z: 1 },
  })

  return (
    <animated.div
      style={{
        transform: to(
          [props.x, props.y, props.z],
          (x, y, z) => `rotate3d(${x}, ${y}, ${z}, 45deg)`
        ),
      }}
    >
      Hello World
    </animated.div>
  )
}

Ranges and Outputs

The to function also accepts a range of input values as the first argument and the output of that range.
Interpolations can be chained, as seen in the example below we change a value 0-1 to 0-360 and then
interpolate it to a rotateZ value.

tsx lines=10
import { useSpring, animated } from '@react-spring/web'

function MyComponent() {
  const props = useSpring({
    from: { x: 0 },
    to: { x: 1 },
  })

  return (
    <animated.div
      style={{
        transform: props.x
          .to([0, 1], [0, 360])
          .to(value => `rotateZ(${value}deg)`),
      }}
    >
      Hello World
    </animated.div>
  )
}

Config

An interpolation can also take a config object as the second argument if using the to function or the first
argument when using the to method of a SpringValue.

import { TablesConfiguration } from '../components/Tables/TablesConfig'
import { INTERPOLATONS_DATA } from '../data/fixtures'

Overriding the global to function

If you decide to, it is possible to override the global Interpolation factory which is what's called when to is used.

ts
import { Globals } from '@react-spring/web'

Globals.assign({
  to: (source, args) => new CustomInterpolation(source, args),
})

Typescript

ts
function to, Output>(
  parents: Input,
  interpolator: (...args: Interpolated) => Output
): Interpolation<Output>

function to(
  parent: FluidValue | Input,
  interpolator: InterpolatorFn
): Interpolation<Output>

function to<Out>(
  parents: FluidValue[],
  config: InterpolatorConfig<Out>
): Interpolation<Animatable<Out>>

function to<Out>(
  parents: Array<FluidValue<number>> | FluidValue<number[]>,
  range: readonly number[],
  output: readonly Constrain<Out, Animatable>[],
  extrapolate?: 'identity' | 'clamp' | 'extend'
): Interpolation<Animatable<Out>>

File: docs/app/routes/docs.advanced.spring-ref.mdx


meta: title: SpringRef | React Spring 'og:title': SpringRef | React Spring 'twitter:title': SpringRef | React Spring 'og:description': An advanced API guide to the SpringRef function in React Spring. 'twitter:description': An advanced API guide to the SpringRef function in React Spring. 'og:url': https://www.react-spring.dev/docs/advanced/spring-ref 'twitter:url': https://www.react-spring.dev/docs/advanced/spring-ref sidebar_position: 5

import { formatFrontmatterToRemixMeta } from '../helpers/meta'

export const meta = formatFrontmatterToRemixMeta(frontmatter)

SpringRef

Our imperative API. You can initialise it via function call, or for better practice use the hook useSpringRef.
For more contextual information for this function and why it's so important, see here.

Usage

Hook

ts
import { animated, useSpring, useSpringRef } from '@react-spring/web'

function MyComponent() {
  const api = useSpringRef()

  const props = useSpring({
    ref: api,
    from: { opacity: 0 },
    to: { opacity: 1 },
  })

  return <animated.div style={props}>Hello World</animated.div>
}

Function call

ts
import { Component, createRef } from 'react'
import { Controller, animated, SpringRef } from '@react-spring/web'

class AnimatedComponent extends Component {
  isShowing = createRef(false)
  api = SpringRef()
  animations = new Controller({ opacity: 0, ref: this.api })

  toggle = () => {
    this.animations.start({ opacity: this.isShowing ? 1 : 0 })

    this.isShowing = !this.isShowing
  }

  render() {
    return (
      <>
        click
        <animated.div style={this.animations.springs}>I will fade</animated.div>
      </>
    )
  }
}

Properties

import { TablesConfiguration } from '../components/Tables/TablesConfig'

Methods

Add

Add a controller to this ref.

ts
add(ctrl: Controller<State>): void

Delete

Remove a controller from this ref.

ts
delete(ctrl: Controller<State>): void

Pause

Pause some or all animations by passing SpringValue keys.

ts
pause(): this
pause(keys: OneOrMore<string>): this
pause(keys?: OneOrMore<string>): this

Resume

Resume some or all animations by passing SpringValue keys.

ts
resume(): this
resume(keys: OneOrMore<string>): this
resume(keys?: OneOrMore<string>): this

Set

Update the state of each controller without animating. Accepts either a partial state object or a
function that returns a partial state object.

ts
set(values: Partial<State>): void
set(values: (index: number, ctrl: Controller<State>) => Partial<State>): void

Start

Start the queued animations of each controller. Alternatively pass a ControllerUpdate object to
update the state of each controller before starting the animations. Or pass a function to edit the
ControllerUpdate depending on the specific Controller.

ts
start(): AsyncResult<Controller<State>>[]
start(props: ControllerUpdate<State>): AsyncResult<Controller<State>>[]
start(props: ControllerUpdateFn<State>): AsyncResult<Controller<State>>[]
start(
props?: ControllerUpdate<State> | ControllerUpdateFn<State>
): AsyncResult<Controller<State>>[]

Stop

Stop some or all of the animations by passing SpringValue keys. Additionall, cancel those animations
by passing a boolean as the first argument and the keys as the second.

ts
stop(): this
stop(keys: OneOrMore<string>): this
stop(cancel: boolean): this
stop(cancel: boolean, keys: OneOrMore<string>): this
stop(keys?: OneOrMore<string>): this
stop(cancel: boolean, keys?: OneOrMore<string>): this

Update

Add the same props to each controller's update queue. Or alternatively generate separate props for each
controller's update queue with a function.

ts
update(props: ControllerUpdate<State>): this
update(props: ControllerUpdateFn<State>): this
update(props: ControllerUpdate<State> | ControllerUpdateFn<State>): this

File: docs/app/routes/docs.advanced.spring-value.mdx


meta: title: SpringValue | React Spring 'og:title': SpringValue | React Spring 'twitter:title': SpringValue | React Spring 'og:description': An advanced API guide to the SpringValue class in React Spring. 'twitter:description': An advanced API guide to the SpringValue class in React Spring. 'og:url': https://www.react-spring.dev/docs/advanced/spring-value 'twitter:url': https://www.react-spring.dev/docs/advanced/spring-value sidebar_position: 4

import { formatFrontmatterToRemixMeta } from '../helpers/meta'

export const meta = formatFrontmatterToRemixMeta(frontmatter)

SpringValue

The very driving force of react-spring. It's a class that can be used to create a single
value that can be animated.

Usage

Basic usage, the SpringValue class you initialise can be used just like our imperative api.
Meanwhile you pass the SpringValue to your animated component. Any type is valid, but only certain types are actually animated.
Types that cannot be animated are basically immediate: true animations. Such types include:
a boolean, a display string like "none", etc.

tsx
import { Component, createRef } from 'react'
import { SpringValue, animated } from '@react-spring/web'

class AnimatedComponent extends Component {
  isShowing = createRef(false)
  springOpacity = new SpringValue(0)

  toggle = () => {
    this.springOpacity.start(isShowing ? 0 : 1)

    this.isShowing = !this.isShowing
  }

  render() {
    return (
      <>
        click
        <animated.div style={{ opacity: this.springOpacity }}>
          I will fade
        </animated.div>
      </>
    )
  }
}

Properties

import { TablesConfiguration } from '../components/Tables/TablesConfig'
import { SPRINGVALUE_PROPERTIES_DATA } from '../data/fixtures'

Methods

Advance

Advance the current animation by a number of milliseconds.

ts
advance(dt: number): void;

Finish

Skip to the end of the current animation.

ts
finish(): this;

Pause

Freeze the active animation in time, as well as any updates merged before resume is called.

ts
pause(): void;

Reset

Restart the animation.

ts
reset(): void;

Resume

Resume the animation if paused.

ts
resume(): void;

Set

Set the current value, while stopping the current animation.

ts
set(value: T | FluidValue<T>): this;

Start

Update this value's animation using the queue of pending props, and unpause the current
animation (if one is frozen). When arguments are passed, a new animation is created, and
the queued animations are left alone.

ts
start(): AsyncResult;
start(props: SpringUpdate<T>): AsyncResult;
start(to: T, props?: SpringProps<T>): AsyncResult;

Stop

Stop the current animation, and cancel any delayed updates. Pass true to call onRest
with cancelled: true.

ts
stop(cancel?: boolean): this

Update

Push props into the pending queue.

ts
update(props: SpringUpdate<T>): this;

TS Glossary

2. Official Technical Reference & Guides (pmndrs/docs)

File: README.md


docs/getting-started/introduction.mdx

Usage

Read

sh
$ npx @pmndrs/docs                                 # the reader: every library, every page
$ npx @pmndrs/docs drei                            # straight into one
$ npx @pmndrs/docs drei/performances/instances     # straight to a page
$ npx @pmndrs/docs search instanced mesh           # one result per line, on stdout

↑↓ drives whichever pane has the focus — the list of pages, or the page itself. ⏎ or ⇥
hands the focus over, esc or ⇥ hands it back, and the lit border says where it is — the
wheel moves whichever pane it points at, focus or no focus. ←→ changes library, b folds the sidebar away, / searches every library at once, o opens the
page in a browser, q quits. Links inside a page are clickable wherever the terminal honours
OSC 8 hyperlinks — iTerm2, Ghostty, WezTerm, Kitty, Windows Terminal.

search is the half a pipe or an agent can use: results read {lib} {path} - {title}, the
shape the MCP server publishes its index in, and nothing found exits 1.
--in drei narrows to one library, --in drei/performances/instances to the matching lines of
one page.

Both read the published llms-full.txt of each library, cached for an hour under
~/.cache/pmndrs-docs — --refresh fetches again. Outside a terminal, a page target is
written to stdout, so npx @pmndrs/docs drei/performances/instances | glow works.

Build

sh
$ cat foo.mdx | npx @pmndrs/docs@latest build               # one HTML fragment, on stdout
$ npx @pmndrs/docs@latest build docs out                    # one .html per .mdx, assets alongside
$ npx @pmndrs/docs@latest build docs out --format website   # the whole website, statically exported

--format fragment (the default) needs nothing but node — no next build, no bundler. A
fragment is the compiled MDX and nothing else: no layout, no stylesheet, no script. Mermaid
diagrams stay fenced blocks, and Sandpack shows its code without the editor.

build --help lists every website option — --libname, --base-path, --icon, --theme-*… Each
one falls back to the environment variable it maps to, the same ones
configuration documents.

Preview a folder of MDX, served

sh
$ curl -sL https://raw.githubusercontent.com/pmndrs/docs/refs/heads/main/preview.sh | \
  MDX="docs" \
  ICON="🥑" \
  sh

Builds the website, then serves it — alongside the MDX folder itself, so relative assets
resolve while you edit. Any option from
configuration goes in the same way, and
VERSION picks a published version of the CLI.

Releasing

Every push to main redeploys docs.pmnd.rs via ci.yml — no changeset needed for that.

Add one (pnpm changeset) only when downstream consumers pinning pmndrs/docs/.github/workflows/build.yml@v4 or @pmndrs/docs@4 should pull the change. It bumps package.json, publishes to npm, and tags vX.Y.Z + vX — so @v4 resolves to the latest.

TL;DR — site-only tweak: skip. Anything consumers see (workflow, build behavior, templates): add one.

Test

Visual tests are performed in the cloud, through chromatic.yml.

You can also replay locally:

sh
$ npx playwright test --update-snapshots
$ npx chromatic --playwright --project-token $CHROMATIC_PROJECT_TOKEN

File: Readme.md

Poimandres

bash
git clone https://github.com/pmndrs/website.git
cd website

yarn
yarn dev

File: readme.md

Poimandres

bash
git clone https://github.com/pmndrs/website.git
cd website

yarn
yarn dev

File: docs/getting-started/introduction.mdx


title: pmndrs/docs nav: 0

A static MDX documentation generator, with a GitHub reusable workflow. It is primarily used for some pmndrs/* projects, but will work for anyone.

Those projects are known to be using this generator.

INSTALL

Pre-requisites:

  • Install nvm, then:
    sh
    $ nvm install
    $ nvm use
    $ node -v # make sure your version satisfies package.json#engines.node
    nb: if you want this node version to be your default nvm's one:
    nvm alias default node
sh
$ git clone https://github.com/pmndrs/docs.git
$ cd docs
$ pnpm install

Configuration

[!IMPORTANT]

Default value is always: "" (think empty).

var description example
MDX* Path to *.mdx folderNB: can be relative or absolute docs or ~/code/myproject/documentation
NEXT_PUBLIC_LIBNAME* Library name React Three Fiber
NEXT_PUBLIC_LIBNAME_SHORT Library short name r3f
NEXT_PUBLIC_LIBNAME_DOTSUFFIX_LABEL Text for the ".docs" suffix link inside the header docs
NEXT_PUBLIC_LIBNAME_DOTSUFFIX_HREF Href for the ".docs" suffix link inside the header https://docs.pmnd.rs
BASE_PATH Base path for the final URL /react-three-fiber
DIST_DIR Path to the output folder (within project) out or docs/out/react-three-fiber
OUTPUT Set to export for static output export
HOME_REDIRECT Where the home should redirect /getting-started/introduction
MDX_BASEURL Base URL for inlining relative images http://localhost:60141or https://github.com/pmndrs/react-three-fiber/raw/master/docs
SOURCECODE_BASEURL Base URL for sourcecode: code path https://github.com/pmndrs/react-three-fiber/tree/main
EDIT_BASEURL Base URL for displaying "Edit this page" URLs https://github.com/pmndrs/react-three-fiber/edit/master/docs
NEXT_PUBLIC_URL Final URL of the published website https://pmndrs.github.io/react-three-fiber
ICON Emoji or image to use as (fav)icon (path local to MDX) 🇨🇭 or /icon.png or /favicon.ico
LOGO Logo src/path (either FQURL or local to MDX path) /logo.png or https://worldvectorlogo.com/r3f.png
GITHUB Github URL https://github.com/pmndrs/react-three-fiber
DISCORD Discord URL https://discord.com/channels/740090768164651008/740093168770613279
THEME_PRIMARY Primary accent color #323e48
THEME_SCHEME Theme scheme content or expressive or fidelity or monochrome or neutral or tonalSpot or vibrant
THEME_CONTRAST Theme contrast -- value between -1 and 1 0 or -1 or 1 or -.6
THEME_NOTE "note" color #1f6feb
THEME_TIP "tip" color #238636
THEME_IMPORTANT "important" color #8957e5
THEME_WARNING "warning" color #d29922
THEME_CAUTION "caution" color #da3633
CONTRIBUTORS_PAT GitHub token for contributors API (see: https://docs.github.com/en/rest/collaborators/collaborators?apiVersion=2022-11-28#list-repository-collaborators) ghp_1234567890

* Required

MDX_BASEURL

Given a advanced/introduction.mdx file in the MDX folder:

md

becomes (for a MDX_BASEURL=http://localhost:60141 value):

md

http://localhost:60141 being the MDX folder served.

[!TIP]
When deployed on GitHub Pages, MDX_BASEURL will typically value something like https://github.com/pmndrs/uikit/raw/main/docs, thanks to build.yml rule.

THEME_*

We implement m3 design system, using material-theme-builder.

[!NOTE]

  • Material Color for more information
  • We currently don't have secondary/tertiary colors (maybe some day).

Usage

dev

sh
$ (
  trap 'kill -9 0' SIGINT

  export _PORT=60141

  export MDX=docs
  export NEXT_PUBLIC_LIBNAME="Poimandres"
  export NEXT_PUBLIC_LIBNAME_SHORT="pmndrs"
  export NEXT_PUBLIC_LIBNAME_DOTSUFFIX_LABEL="docs"
  export NEXT_PUBLIC_LIBNAME_DOTSUFFIX_HREF="https://docs.pmnd.rs"
  export BASE_PATH=
  export DIST_DIR=
  export OUTPUT=
  export HOME_REDIRECT=
  export MDX_BASEURL=http://localhost:$_PORT
  export SOURCECODE_BASEURL="vscode://file$(pwd)"
  export EDIT_BASEURL="vscode://file$(pwd)/docs"
  export NEXT_PUBLIC_URL=
  export ICON=
  export LOGO=gutenberg.jpg
  export GITHUB=https://github.com/pmndrs/docs
  export DISCORD=https://discord.com/channels/740090768164651008/1264328004172255393
  export THEME_PRIMARY="#323e48"
  export THEME_SCHEME="tonalSpot"
  export THEME_CONTRAST="0"
  export THEME_NOTE="#1f6feb"
  export THEME_TIP="#238636"
  export THEME_IMPORTANT="#8957e5"
  export THEME_WARNING="#d29922"
  export THEME_CAUTION="#da3633"
  export CONTRIBUTORS_PAT=

  kill $(lsof -ti:"$_PORT")
  npx serve $MDX -p $_PORT --no-port-switching --no-clipboard &

  pnpm run dev &

  wait
)

Then go to: http://localhost:3000

[!TIP]
If HOME_REDIRECT= empty, / will not redirect, and instead displays an index of libraries.

build

sh
$ (
  trap 'kill -9 0' SIGINT

  rm -rf out

  export _PORT=60141

  export MDX=docs
  export NEXT_PUBLIC_LIBNAME="Poimandres"
  export NEXT_PUBLIC_LIBNAME_SHORT="pmndrs"
  export NEXT_PUBLIC_LIBNAME_DOTSUFFIX_LABEL="docs"
  export NEXT_PUBLIC_LIBNAME_DOTSUFFIX_HREF="https://docs.pmnd.rs"
  export BASE_PATH=
  export DIST_DIR=
  export OUTPUT=export
  export HOME_REDIRECT=/getting-started/introduction
  export MDX_BASEURL=http://localhost:$_PORT
  export SOURCECODE_BASEURL=
  export EDIT_BASEURL=
  export NEXT_PUBLIC_URL=
  export ICON=
  export LOGO=gutenberg.jpg
  export GITHUB=https://github.com/pmndrs/docs
  export DISCORD=https://discord.com/channels/740090768164651008/1264328004172255393
  export THEME_PRIMARY="#323e48"
  export THEME_SCHEME="tonalSpot"
  export THEME_CONTRAST="0"
  export THEME_NOTE="#1f6feb"
  export THEME_TIP="#238636"
  export THEME_IMPORTANT="#8957e5"
  export THEME_WARNING="#d29922"
  export THEME_CAUTION="#da3633"
  export CONTRIBUTORS_PAT=

  pnpm run build

  kill $(lsof -ti:"$_PORT")
  npx serve $MDX -p $_PORT --no-port-switching --no-clipboard &

  npx serve out &

  wait
)

http://localhost:3000

CLI

No clone, no install — the published CLI does the same build:

sh
$ cd ~/code/pmndrs/react-three-fiber
$ (
  trap 'kill -9 0' SIGINT

  export _PORT=60141

  export NEXT_PUBLIC_LIBNAME="React Three Fiber"
  export NEXT_PUBLIC_LIBNAME_SHORT="r3f"
  export BASE_PATH=/toto
  export HOME_REDIRECT=/getting-started/introduction
  export MDX_BASEURL=http://localhost:$_PORT
  export ICON=🇨🇭
  export GITHUB=https://github.com/pmndrs/react-three-fiber

  npx -y @pmndrs/docs@latest build docs docs/out --format website

  kill $(lsof -ti:"$_PORT")
  npx serve docs -p $_PORT --no-port-switching --no-clipboard &

  npx -y serve docs/out &

  wait
)

Then go to: http://localhost:3000

Every option above has a flag too — npx @pmndrs/docs@latest build --help lists them.

Agents

llms.txt dumps and the pmndrs MCP server moved to their own page: Agents.