Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Create a Button Shake Animation in React Native

    react-nativeReact Native

    In this lesson we'll use Animated.timing and TouchableWithoutFeedback to create an animatable button. We'll learn how to use interpolate to create a non-linear animation. When our button is pressed it will shake from side to side.



    Become a Member to view code

    You must be a Pro Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    orLog In




    We'll start by creating a component able mount cycle method and creating a vista animation equals a new animated value with the default of zero. Now, taking a quick look at our current application structure. We have a wrapping view container with a touchable without feedback, which inside of it will have the button that we style.

    This case it's an animated view with some text inside of it that says, "Press to wiggle." Our styles that are applied to this are padding vertical and padding horizontal to create some spacing around the text. A border radius of 30 to create the rounded edges, and then we have a background color. We'll also set our text color to white.

    To make our wiggle we'll use interpolate. We'll create a variable called "const interpolated," equals this.animation.interpolate, which will receive an object which will have our input range and our output range.

    To make our button wiggle, we'll need to start at zero. We'll go left, -15, back to zero, then right 15, back to zero, back left -15, and then back to zero. We can plan our wiggle based upon our output range and then determine our input range from that. First will be zero. Second will be 05. Third will be one, then 1.5, two, 2.5, and then three.

    Now, we'll create our style, so we say const style equals transform, which is an array of objects. In this case we'll use translate X and apply our interpolated that we just created. Then we'll apply the style to our button. When our button is pressed we'll have it call this touch trigger animation function.

    We'll now go create our animation, so the first thing we'll need to do is type this.animation.setvalue to zero. In case the button is pressed multiple times, I want you to reset our animation back to zero. We'll then do animated.timing, which will take our animation, so this.animation. Then an object to describe what we need to do.

    We'll have our wiggle over 400 milliseconds. Because our input range ends at three, we'll say two value of three. Then we'll add ease and easing.bounce to create a little bounce effect. To trigger our animation, we just need to call start. Now when I refresh and press on our button, it will shake from side to side.