Animated Sliding Tab bar in React Native

Aditya Singh
Webtips
Published in
3 min readNov 27, 2018

Bored of that lifeless tab bar in react native? Let’s bring life back into it. I have also put up a video regarding this on youtube. Skip it, if you prefer reading.

Still here? Great! We start by creating two tabs in the top section:

We need an overlay in our parent wrapper that will slide from one tab to the other. This overlay should be absolutely positioned w.r.t the parent wrapper of tabs.

Our goal is to get the x coordinate of tab one and two and then change the translateX value of this overlay to it based on the currently active tab.

To do that, we first need to get the x coordinate of these two tabs and store them in a state variable. We use onLayout on TouchableOpacity and then get the x coordinate value from it. Since, we do not know these values when the component loads, we simply initialise it with 0 . Also, we define a new active state, which gives us the index of the currently active tab. We change this state based on the onPress event of the individual tabs.

At this point, we are good to Slide our overlay between these two tabs.

Let’s create a new function handeSlide(type) which takes in one param i.e. type . This type variable will tell us which x coordinate should the overlay slide to. Also, we change our overlay to Animated.View and add a new style translateX to it which will be an animated value. Its value will change based on the current active tab.

Phewww! We now have our overlay sliding between tabs based on which tab the user has clicked on.

It is now time to have some content slide just like our tabs do.

We start by adding a ScrollView right underneath our parent wrapper for tabs and add two View nodes to it, once for each tab. The first View node is for tab one and the other one is for tab two.

We cannot use flexDirection: 'row' to align these two views horizontally. Because then it wouldn’t work the way we want it to. Instead, we initially perform translate operations on the second node.

The first translate is translateX , it will translate the view along the x-axis and takes it out of the screen.

The second translate is translateY , why this? Well, since our second view node is right underneath our first view node, we want it to translate upward and align with the first view node. The value of translateY would be equal to the negative height of view node.

We have to modify our handleSlide(type)function as well in order for these two views to switch their translate values.

Done! We now have an animated sliding tab bar in our react native app.

Here’s a Snack

Github repo: https://github.com/morfsys/react-native-animated-tabbar

I work as a Javascript developer at Morfsys. I love to write about technology, science, and more.

Follow me for more such stuff!

--

--