How to Animate a Header View on Scroll With React Native Animated

Published on Oct 1, 2020

9 min read

EXPO

cover_image

The Animated library from React Native provides a great way to add animations and give app users a smooth and friendlier experience.

In this tutorial, let's explore a way to create a header view component that animates on the scroll position of the ScrollView component from React Native. We will go through the basics of creating a new Animated value as well as explaining the significance of functions and properties like interpolation, extrapolate, contentOffset, and so on.

The source code is available at GitHub.

Prerequisites

🔗

To follow this tutorial, please make sure you are familiarized with JavaScript/ES6 and meet the following requirements on your local dev environment.

  • Node.js version >= 12.x.x installed
  • Have access to one package manager such as npm or yarn
  • expo-cli version installed or use npx

The example in the following tutorial is based on Expo SDK 38.

Installing dependencies

🔗

Start by creating a new React Native app generated with expo-cli. Do note that all the code mentioned in this tutorial works with plain React Native apps as well. Open up a terminal window and execute the following command:

npx expo-cli init animate-header-example
# after the project is created, navigate into the directory
cd animate-header-example

To handle devices with notch both on iOS and Android operating systems, let's install some libraries first. These libraries are going to add automatic padding on notch devices such that the main view of the app does not intersect with a safe area on notch-enabled devices. Run:

expo install react-native-safe-area-view react-native-safe-area-context

To use safe area views, wrap the root of the React Native app with SafeAreaProvider from the react-native-safe-area-context library. Open App.js and modify the it as shown below:

1import React from 'react';
2import { Text, View } from 'react-native';
3import { SafeAreaProvider } from 'react-native-safe-area-context';
4
5export default function App() {
6 return (
7 <SafeAreaProvider>
8 <View style={{ flex: 1, alignItems: 'center' }}>
9 <Text>Open up App.js to start working on your app!</Text>
10 </View>
11 </SafeAreaProvider>
12 );
13}

Next, wrap the contents of the App component with SafeAreaView from the react-native-safe-area-view library. It is going to have a style prop with a flex of value 1 and another prop called forceInset. It’s important we add this, especially for some Android devices which might not behave as expected. This prop is going to force the application to add an inset padding on the content view. Setting the value of top: always will always imply that padding is forced at the top of the view.

1// ... other import statements
2import SafeAreaView from 'react-native-safe-area-view';
3
4export default function App() {
5 return (
6 <SafeAreaProvider>
7 <SafeAreaView style={{ flex: 1 }} forceInset={{ top: 'always' }}>
8 <View style={{ flex: 1, alignItems: 'center' }}>
9 <Text>Open up App.js to start working on your app!</Text>
10 </View>
11 </SafeAreaView>
12 </SafeAreaProvider>
13 );
14}

Here is what happens on an Android device when forceInset is not used on SafeAreaView:

ss1

And with the forceInset prop applied:

ss2

On iOS, the behavior is as expected:

ss3

The last step in this section is to create a new component file called AnimatedHeader.js inside the components/ directory. For now, it is going to return nothing.

1import React from 'react';
2import { Animated, View } from 'react-native';
3
4const AnimatedHeader = () => {
5 return null;
6};
7
8export default AnimatedHeader;

Make sure to import it in the App.js file:

1// ... after other import statements
2import AnimatedHeader from './components/AnimatedHeader';

Creating an animated header component

🔗

The animation on the position of the scroll on a ScrollView component is going to have an Animated.Value of 0. To create an animation, Animated.Value is required. In the App.js file, import useRef from the React library. Then, define a variable called offset with a new Animated.Value. To use the Animated library from React Native, import it as well.

1import React, { useRef } from 'react';
2import { Text, View, Animated } from 'react-native';
3// ...other import statements
4
5export default function App() {
6 const offset = useRef(new Animated.Value(0)).current;
7
8 // ...
9}

For this example, it is not required to use the useRef hook; however, if you are looking forward to modifying the animated value, it is recommended to use useRef. It provides a current property that is persisted throughout a component's lifecycle.

The value of the offset can now be passed as a prop to the AnimatedHeader component.

1export default function App() {
2 const offset = useRef(new Animated.Value(0)).current;
3
4 return (
5 <SafeAreaProvider>
6 <SafeAreaView style={{ flex: 1 }} forceInset={{ top: 'always' }}>
7 {/* Add the following AnimatedHeader */}
8 <AnimatedHeader animatedValue={offset} />
9 <View style={{ flex: 1, alignItems: 'center' }}>
10 <Text>Open up App.js to start working on your app!</Text>
11 </View>
12 </SafeAreaView>
13 </SafeAreaProvider>
14 );
15}

To access the safe area inset value inside the AnimatedHeader component, the library react-native-safe-area-context provides a hook called useSafeAreaInsets(). This hook returns a safe area insets object with the following values:

1{
2 top: number,
3 right: number,
4 bottom: number,
5 left: number
6}

The inset value of top is going to be manipulated when defining the animated header.

First, let's import this hook in the AnimatedHeader.js file and then define a fixed HEADER_HEIGHT constant that is going to be the initial height of the Animated.View.

1// ... other import statements
2import { useSafeAreaInsets } from 'react-native-safe-area-context';
3
4const HEADER_HEIGHT = 200;
5
6const AnimatedHeader = ({ animatedValue }) => {
7 const insets = useSafeAreaInsets();
8
9 return null;
10};

To animate the height of the header view on the scroll, we are going to use interpolation. The interpolate() function on Animated.Value allows an input range to map to a different output range.

In the current scenario, when the user scrolls, the interpolation on Animated.Value is going to change the scale of the header to slide to the top on scroll along the y-axis. This effect is going to minimize the initial value of the height of Animated.View.

The interpolation must specify an extrapolate value. This determines the scaling of the header’s height to be visible at the last value in outputRange. There are three different values for extrapolate available, but we are going to use clamp.

Begin by declaring a variable called headerHeight that is going to have the value of interpolation. The Animated.Value is the prop animatedValue coming from the parent component.

The inputRange is going to be 0 to the HEADER_HEIGHT plus the top inset. The outputRange is to be the HEADER_HEIGHT plus the top inset to the top inset plus 44.

1const AnimatedHeader = ({ animatedValue }) => {
2 const insets = useSafeAreaInsets();
3
4 const headerHeight = animValue.interpolate({
5 inputRange: [0, HEADER_HEIGHT + insets.top],
6 outputRange: [HEADER_HEIGHT + insets.top, insets.top + 44],
7 extrapolate: 'clamp'
8 });
9
10 // ...
11};

Now, let's add an Animated.View to render from this component. It is going to use position: absolute to help cover the background behind the status bar as well as the same color as the whole header.

1const AnimatedHeader = ({ animatedValue }) => {
2 // ...
3 return (
4 <Animated.View
5 style={{
6 position: 'absolute',
7 top: 0,
8 left: 0,
9 right: 0,
10 zIndex: 10,
11 height: headerHeight,
12 backgroundColor: 'lightblue'
13 }}
14 />
15 );
16};

This section ends with the following output:

ss4

Manipulating the ScrollView

🔗

In the App.js file, a ScrollView component is going to be displayed beneath the header component and, in return, it is going to display a list of mocked data.

For this example, I've prepared a bare minimum list of book titles in a separate file called data.js.

1const DATA = [
2 {
3 id: 1,
4 title: 'The Hunger Games'
5 },
6 {
7 id: 2,
8 title: 'Harry Potter and the Order of the Phoenix'
9 },
10 {
11 id: 3,
12 title: 'To Kill a Mockingbird'
13 },
14 {
15 id: 4,
16 title: 'Pride and Prejudice'
17 },
18 {
19 id: 5,
20 title: 'Twilight'
21 },
22 {
23 id: 6,
24 title: 'The Book Thief'
25 },
26 {
27 id: 7,
28 title: 'The Chronicles of Narnia'
29 },
30 {
31 id: 8,
32 title: 'Animal Farm'
33 },
34 {
35 id: 9,
36 title: 'Gone with the Wind'
37 },
38 {
39 id: 10,
40 title: 'The Shadow of the Wind'
41 },
42 {
43 id: 11,
44 title: 'The Fault in Our Stars'
45 },
46 {
47 id: 12,
48 title: "The Hitchhiker's Guide to the Galaxy"
49 },
50 {
51 id: 13,
52 title: 'The Giving Tree'
53 },
54 {
55 id: 14,
56 title: 'Wuthering Heights'
57 },
58 {
59 id: 15,
60 title: 'The Da Vinci Code'
61 }
62];
63
64export default DATA;

The next step is to import this file in App.js. Also, import the ScrollView component from React Native.

1//...
2import { ScrollView, Text, View, Animated } from 'react-native';
3
4import DATA from './data';

Next, modify the contents of the App component. The important prop to note below in the ScrollView component is the onScroll prop. Mapping gestures like scrolling directly to an animated value can be done by using Animated.Event. This type of event function is passed as the value to the onScroll prop.

Animated.Event accepts an array of objects as the first argument which is going to be the contentOffset, which tells the current position of the scrolling view. It changes every time the user scrolls up or down. The value of contentOffset along the y-axis is going to be the same Animated.Value that is used to interpolate the height of the AnimatedHeader component.

It is recommended that you pass the second argument of useNativeDriver in Animated.Event .

1export default function App() {
2 const offset = useRef(new Animated.Value(0)).current;
3
4 return (
5 <SafeAreaProvider>
6 <SafeAreaView style={{ flex: 1 }} forceInset={{ top: 'always' }}>
7 <AnimatedHeader animatedValue={offset} />
8 <ScrollView
9 style={{ flex: 1, backgroundColor: 'white' }}
10 contentContainerStyle={{
11 alignItems: 'center',
12 paddingTop: 220,
13 paddingHorizontal: 20
14 }}
15 showsVerticalScrollIndicator={false}
16 scrollEventThrottle={16}
17 onScroll={Animated.event(
18 [{ nativeEvent: { contentOffset: { y: offset } } }],
19 { useNativeDriver: false }
20 )}
21 >
22 {DATA.map(item => (
23 <View
24 key={item.id}
25 style={{
26 marginBottom: 20
27 }}
28 >
29 <Text style={{ color: '#101010', fontSize: 32 }}>
30 {item.title}
31 </Text>
32 </View>
33 ))}
34 </ScrollView>
35 </SafeAreaView>
36 </SafeAreaProvider>
37 );
38}

Here is the output after this step on an iOS device:

ss5

On Android:

ss6

Conclusion

🔗

I hope you had fun reading this tutorial. If you are trying the Animated library from React Native for the first time, wrapping your head around it might take a bit of time and that's the part of the process.

Some of the important topics covered in this post are listed as links for further reading below:

Originally published at Jscrambler.


More Posts

Browse all posts

Aman Mittal author

I'm a software developer and a technical writer. On this blog, I write about my learnings in software development and technical writing.

Currently, working maintaining docs at 𝝠 Expo. Read more about me on the About page.


Copyright ©  2019-2024 Aman Mittal · All Rights Reserved.