DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 968,873 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Bryce Dorn
Bryce Dorn

Posted on • Updated on

Triggering shake animations in react-pose

Shakin' it

I couldn't find a good how-to for this so thought I'd write one. I'm working on a game and react-pose has been awesome for creating smooth animations between different component states. But what if I want to animate a component that isn't changing state?

Vanilla pose supports this natively, as this aligns closely with the way it's architected: poser.set('nameOfPose'). On the flipside, react-pose is built around transitioning between states, e.g. left or right. So how do I trigger this animation without changing its state or position?

The answer lies in a few key fundamentals:

1. applyAtStart/applyAtEnd

applyAtStart and applyAtEnd accept style properties to apply either at the start or end of an animation.

Provides an internal memory for the pose allowing for temporary movement. In the case of this shake animation, this lets us move the element from its initial x position to start the animation then return it to that same position afterward.

2. poseKey

If poseKey changes, it’ll force the posed component to transition to the current pose, even if it hasn’t changed.

The trigger needed to fire the animation; it can be any state variable as long as it's updated when you want the animation to occur.

3. spring

The transition that does the actual shaking: once moved from its resting position the spring oscillates back and forth.

Putting all of this together:

On each button click the guesses count will decrement, triggering the poseKey update to force the shake pose (even though it's already in that pose). This shifts it to the left and back, but due to the spring it will shake a bit before coming to a stop.

And there you have it! Hopefully someone may find this useful rather than digging through the docs a bit. Stay tuned for the game I'm making that will be using this!

Top comments (0)

In defense of the modern web

I expect I'll annoy everyone with this post: the anti-JavaScript crusaders, justly aghast at how much of the stuff we slather onto modern websites; the people arguing the web is a broken platform for interactive applications anyway and we should start over;

React users; the old guard with their artisanal JS and hand authored HTML; and Tom MacWright, someone I've admired from afar since I first became aware of his work on Mapbox many years ago. But I guess that's the price of having opinions.