Nowadays, animations are an essential part of mobile apps and websites.
When done properly, they make React Native applications look smoother, attract users’ attention, and increase user engagement. One of the most famous animations is the lovely heart created by the Instagram team. Let me quickly show you how to create it in React Native.
Every animation consists of two main elements: we need to have an object (an SVG element or JSX object) that will be in motion and the definition of this motion. There are many libraries that can help us – let’s start with defining our heart object with a little help of react-native-vector-icons. This library has a lot of available SVG icons. Then, we will add some motion using react-native-animatable library, which is a wrapper for React Native’s core animation library, Animated.
Part I: Installation
Let’s start with installing the necessary dependencies:
npm install react-native-vector-icons or yarn add react-native-vector-icons npm install react-native-animatable or yarn add react-native-animatable
Then we need to link the react-native-vector-icons library. I recommend doing it with React Native CLI:
react-native link react-native-vector-icons
In case you have any problems using those libraries, please follow the instructions on the GitHub repo of each library.
After all the operations complete, you can proceed with starting your application:
react-native run-ios react-native run-android
Part II: Boilerplate
Let’s start with importing the libraries inside our component:
import * as Animatable from 'react-native-animatable' import Icon from 'react-native-vector-icons/AntDesign'
Then, we combine those 2 libraries together, by wrapping the Icon in the Animatable Component:
const AnimatedIcon = Animatable.createAnimatableComponent(Icon)
This way, we can apply animations from the react-native-animatable library on the vector Icon element. Now, further inside the file, we’ll use the AnimatedIcon component.
Part III: PhotoCard Component
Let’s go through the render function first:
At the beginning of the render function, we check the value of a liked state. Its value has a direct impact on the heart icon and the name, since we need two separate icons for full and empty heart.
The topmost container includes:
- Card: TouchableOpacity element,
- AnimatedIcon component: for bigger heart animation,
- AnimatedIcon component: for small heart animation,
- Image element: includes the photo,
- Text element: description of the Image.
All the styles for the PhotoCard component can be found here:
In order to hook the AnimatedIcon components to functions which handle animations, we add a ref prop to each component. Then we add the bouncing animations to the references, and their type depends on whether the component is in the liked state or not:
You can check out the full code and the result in your browser with expo: https://snack.expo.io/@karniej/cGhvdG