Search code examples
react-spring

Animated button with React Spring


I am coming from a React-pose background and like to try React-spring. I have a really simple case which I'd like to transfer to be used with React-spring.

I have the case written in a Codesanbox using React-pose, https://codesandbox.io/s/4wxzm60nk9

I've tried converting this myself, but I just end up confusing myself. Especially now when trying to do it with their hooks API. All help that I can get is super appriciated.

Thank you.


Solution

  • I just made an animated button yesterday, so I refactored it to change its size.

    import React, {useState} from "react";
    import { Spring, animated as a } from 'react-spring/renderprops';
    
    const SpringButton = () => {
      const [pressed, setPressed] = useState(false);
      return (
      <Spring native from={{scale: 1}} to={{scale: pressed? 0.8 : 1}}>
        {({scale}) => (
          <a.button 
            style={{
              backgroundColor: 'red', 
              height: '100px', 
              width: '100px', 
              color: 'rgb(255, 255, 255)',
              transform: scale.interpolate(scale => `scale(${scale})`)
              }}
            onMouseDown={() => setPressed(true)}
            onClick={() => setPressed(false)}
            onMouseLeave={() => setPressed(false)}
          >
            Click me
          </a.button>
        )}
      </Spring>
      );
    }
    

    Its not the hook interface yet, but I think it helps you to understand how it works. I t also uses the quicker native rendering. The event handling a bit different from react-pose. And you can tweek the config as well if you want the animation really springy.

    import {config} from 'react-spring/renderprops';
    <Spring config={config.wobbly} ...>
    

    https://codesandbox.io/s/7zlrkv4kjj