SoFunction
Updated on 2025-04-07

Basic usage of front-end framework react-spring

Install

react-spring's official documentation--Link

yarn add @react-spring/web

application

Component animation

const springs = useSpring({
  from: { x: 0 },
  to: { x: 100 },
})
return (
  <
    style={{
      width: 80,
      height: 80,
      background: '#ff6d6d',
      borderRadius: 8,
      ...springs,
    }}
  />
)

The component declares that the component can define from and to change the x coordinates of the component, thereby moving in the default time to form an animation.

API control spring

({
  from: {
    x: 0,
  },
  to: {
    x: 100,
  },
})

Concept introduction

react-spring is encapsulated by SpringValues ​​and animated components. An animated component updates the component state through the parameters of the style attribute, and this process does not cause the component to render. It is implemented based on the principle of Higher-Order component (HOC), which is based on a set of elements formed by the parameter categories passed on the div or insert SpringValues ​​through the hooks function to achieve the effect you want.

Animating elements

Animated components can be used on any web element, however, since the original element is used, animated components are used on specific targets.

import { animated } from '@react-spring/web' 
// ✅ This will work because `div` is a web element 
< /> 
// ❌ This will not work because `mesh` is not a web element. 
< />

If you have used framer-motion before, you should be familiar with the .grammatical structure of components.

So when you can use it proficiently, in most cases you can write the effect you want in element. There is no special writing method for react-spring in style. Common examples such as css modules tailwind writing method and react-spring can be supported because the animated component can accept attributes in the original element, such as className.

If you plan to use the css library to modify components, the styled function supports you doing this, combining animated components and styled together like nested components.

import { styled } from '@stitches/react' 
const MyModal = styled(, { 
  width: '40vw', 
  height: '20vh', 
  borderRadius: '8px', 
  backgroundColor: '$white80', 
})

Controllers & Springs & API

If you have used the useSpring function, then you are more familiar with the following code

const [styles, api] = useSpring(() =&gt; ({ 
  x: 0, 
  y: 0, 
  backgroundColor: '#ff0000', 
  scale: [1, 1, 1], 
  config: { 
    precision: 0.0001, 
  }, 
}))

The useSpring function returns an array object containing two elements styles``api. It is an object containing SpringValue, which is a dynamic key, of course, you define these keys yourself.

For example:

type SpringValues<SpringConfig extends Record<string, any> = { 
  [Key in keyof OnlyAnimatableKeys<SpringConfig>]: SpringValue 
}

In the above example, OnlyAnimatableKeys is just a simple configuration parameter with keys such as x,y, backgroundColor, scale. So because we know that these keys are variable, these keys will become the simple type parameters in this function.

Controller

So what is a Controller? In fact, each spring can be regarded as a Controller. Therefore, when you use the useSpring function to create a Controller object or pass multiple parameters into the useSprings function, then you create multiple Controller objects.

These Controller objects are used to manage SpringValue objects created through configuration parameters. These methods are similar to those in SpringValue classes. The main methods in Controllers, such as start``stop``pause, are used to manage SpringValue objects in arrays.

// The set method from the Controller class 
set(values) { 
  for (const key in values) { 
    const value = values[key] 
    if (!(value)) { 
      [key].set(value) 
    } 
  } 
} 
// Would be used like this 
({ 
  x: 0, 
  scale: [0,0,0] 
})

The object configured by the useSpring function and the Controller class construct the first parameter is the same, so you can know that in the react environment, the useSpring function operates the life cycle of the Controller class and adds it to the controller object through the SpringRef method. SpringRef provides a very simple and quick way to manage one or more Controller class objects. In this way, compared with the two, you can ignore the hook method and directly use the Controller class method.

Spring value

SpringValues ​​can meet normal interaction requirements. Their parameters are explicitly passed into the animated component. These parameters can be added without being named when the component is used.

const { 
  backgroundColor, // SpringValue<string> 
  o, // SpringValue<number> 
  trans, // SpringValue<number[]> 
} = useSpring({ 
  backgroundColor: '#00ff00', 
  o: 0, 
  trans: [0, 1, 2], 
})

This is because those using your named keys in Controller and SpringValue, it only cares about the value of the parameter type you pass in. In the SpringValue class, we can control the entire life cycle during the motion, from the triggering of events through different types of ways, SpringValue is the driving force during the motion.

Imperative API

These imperative APIs allow you to not need to update your animations when the page is rendered, which is very beneficial for animations, so that you don’t have to tie the animations and component life cycles together, so that the animations can make rapid changes based on the user’s ideas.

In fact, simply attaching the SpringRef object as a parameter in the Controller function, you can add SpringRef to multiple Controllers, so that a set of animations can be generated. This idea is similar to the useChain function.

Let's take a look at the specific differences between SpringValue and Controller

import { useState } from 'react' 
import { useSpring, useSpringRef, animated } from '@react-spring/web' 
const ApiComponent = () => { 
  const api = useSpringRef() 
  const springs = useSpring({ 
    ref: api, 
    from: { x: 0 }, 
  }) 
  const handleClick = () => { 
    ({ 
      to: { 
        x: () === 100 ? 0 : 100, 
      }, 
    }) 
  } 
  return ( 
    <div className="flex-container"> 
      <         
      onClick={handleClick}         
      style={{           
        width: 80,           
        height: 80,           
        background: '#ff6d6d',           
        borderRadius: 8,           
        ...springs,         
      }}       
  	/> 
  	<span>Render ID – {()}</span> 
  </div> 
  ) 
} 
const StateComponent = () => { 
  const [forward, setForward] = useState(false) 
  const springs = useSpring({ 
    x: forward ? 100 : 0, 
  }) 
  const handleClick = () => { 
    setForward(s => !s) 
  } 
  return ( 
    <div className="flex-container"> 
      <         
      onClick={handleClick}         
      style={{           
        width: 80,           
        height: 80,           
        background: '#ff6d6d',           
        borderRadius: 8,           
        ...springs,         
      }}       
  	/>  
  	<span>Render ID – {()}</span> 
  </div> 
  ) 
} 
export default function MyComponent() { 
  return ( 
    <div className="flex-container--column"> 
      <ApiComponent /> 
    	<StateComponent /> 
    </div> 
  ) 
}

One way is to change the animation using the API of the Controller, and the second way is to implement the parameter value in SpringValue. When the page is re-rendered, the animation is implemented according to the different values.

The above is the detailed content of the basic usage of react-spring for front-end framework. For more information about react spring for front-end framework, please pay attention to my other related articles!