DEV Community

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)