reactjsreact-spring

Animate current value += something in React Spring


Is there a way to animate the current value += something ?
I'm trying to do a half rotation on each click.

// Toggling rotating somewhere else
const [rotating, setRotating] = useState(false);

// Rotate
const rotation = useSpring({
  rotation: rotating ? CURRENT += Math.PI : CURRENT
});

Solution

  • I ended up using useRef and manually updating the value on each iteration.

    https://codesandbox.io/s/interesting-haslett-emreol?file=/src/App.js

    import { useRef } from 'react'
    import { Canvas } from '@react-three/fiber'
    import { useSpring, a, config } from '@react-spring/three'
    
    function Box(props) {
      return (
        <mesh {...props}>
          <tetrahedronGeometry args={[2, 2]} />
          <meshStandardMaterial color="orange" flatShading={true} />
        </mesh>
      )
    }
    
    export default function App() {
      const currentRotation = useRef(0)
      const { rotation } = useSpring({
        from: {
          rotation: 0
        },
        config: config.gentle
      })
      return (
        <Canvas>
          <directionalLight position={[3, 2, 2]} intensity={1.5} />
          <spotLight position={[-1, 0, 5]} intensity={0.5} />
          <a.group
            rotation-y={rotation}
            onClick={() => {
              rotation.start({
                to: currentRotation.current - Math.PI / 4
              })
              currentRotation.current -= Math.PI / 4
            }}>
            <Box position={[0, 0, 0]} />
          </a.group>
        </Canvas>
      )
    }