Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Animated button with React Spring

Tags:

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.

like image 421
Martin Nordström Avatar asked Jan 20 '26 22:01

Martin Nordström


1 Answers

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

like image 92
Peter Ambruzs Avatar answered Jan 23 '26 07:01

Peter Ambruzs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!