• Stars
    star
    113
  • Rank 310,115 (Top 7 %)
  • Language
    Java
  • Created over 4 years ago
  • Updated almost 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

🤯 React Native Animated Header with ScrollView

React Native ScrollView Animated Header

React Native Animated Header App with ScrollView

Animated header is the most common design pattern in today’s apps. Animations are an important part of mobile applications.

Getting Started

  1. Clone this repository
git clone https://github.com/Gapur/react-native-scrollview-animated-header.git
  1. Install dependencies
yarn
  1. Launch app
npm run ios # for npm

Making Magic Code

We need to define some constants for the animated header which will be used to interpolate the scroll position value.

const HEADER_MAX_HEIGHT = 240;
const HEADER_MIN_HEIGHT = 84;
const HEADER_SCROLL_DISTANCE = HEADER_MAX_HEIGHT - HEADER_MIN_HEIGHT;

I will display user data with ScrollView component. So We should to change App.js file like this:

const HEADER_MAX_HEIGHT = 240; // max header height
const HEADER_MIN_HEIGHT = 84; // min header height
const HEADER_SCROLL_DISTANCE = HEADER_MAX_HEIGHT - HEADER_MIN_HEIGHT; // header scrolling value

// create array by 10 fake user data
const DATA = Array(10)
  .fill(null)
  .map((_, idx) => ({
    id: idx,
    avatar: faker.image.avatar(),
    fullName: `${faker.name.firstName()} ${faker.name.lastName()}`,
  }));

function App() {
  const renderListItem = (item) => (
    <View key={item.id} style={styles.card}>
      <Image style={styles.avatar} source={{uri: item.avatar}} />
      <Text style={styles.fullNameText}>{item.fullName}</Text>
    </View>
  );

  return (
    <SafeAreaView style={styles.saveArea}>
      <ScrollView contentContainerStyle={{ paddingTop: HEADER_MAX_HEIGHT - 32 }}> // it should be under the header 
        {DATA.map(renderListItem)}
      </ScrollView>
    </SafeAreaView>
  );
}

We need to create the header under the ScrollView. We will use Animated.View

<Animated.View
  style={[
    styles.topBar,
    {
      transform: [{scale: titleScale}, {translateY: titleTranslateY}],
    },
  ]}>
  <Text style={styles.title}>Management</Text>
</Animated.View>

Magic Animation

React Native provides Animated API for animations. Animated API focuses on declarative relationships between inputs and outputs, with configurable transforms in between, and start/stop methods to control time-based animation execution.

We are going to use Animated.ScrollView to make the scroll view, and attach a callback to listen to the onScroll event when it is changed. Then, using interpolation to map value between the y-axis and opacity. The interpolation maps input ranges to output ranges, typically using a linear interpolation but also supports easing functions.

Let’s update our App.js file with the following lines of code:

const scrollY = useRef(new Animated.Value(0)).current; // our animated value

// our header y-axis animated from 0 to HEADER_SCROLL_DISTANCE,
// we move our element for -HEADER_SCROLL_DISTANCE at the same time.
const headerTranslateY = scrollY.interpolate({
  inputRange: [0, HEADER_SCROLL_DISTANCE],
  outputRange: [0, -HEADER_SCROLL_DISTANCE],
  extrapolate: 'clamp',
});

// our opacity animated from 0 to 1 and our opacity will be 0
const imageOpacity = scrollY.interpolate({
  inputRange: [0, HEADER_SCROLL_DISTANCE / 2, HEADER_SCROLL_DISTANCE],
  outputRange: [1, 1, 0],
  extrapolate: 'clamp',
});
const imageTranslateY = scrollY.interpolate({
  inputRange: [0, HEADER_SCROLL_DISTANCE],
  outputRange: [0, 100],
  extrapolate: 'clamp',
});

// change header title size from 1 to 0.9
const titleScale = scrollY.interpolate({
  inputRange: [0, HEADER_SCROLL_DISTANCE / 2, HEADER_SCROLL_DISTANCE],
  outputRange: [1, 1, 0.9],
  extrapolate: 'clamp',
});
// change header title y-axis
const titleTranslateY = scrollY.interpolate({
  inputRange: [0, HEADER_SCROLL_DISTANCE / 2, HEADER_SCROLL_DISTANCE],
  outputRange: [0, 0, -8],
  extrapolate: 'clamp',
});

Above, we use useRef to persist Animated value. useRef returns a mutable ref object whose .current property is initialized to the passed argument.

Next, We need to update Animated value when we are scrolling ScrollView. We will catch event by Animated.event. It maps directly to animated value scrollY and update it when we are panning or scrolling.

We can use the native driver by specifying useNativeDriver: true in our animation configuration.

Let’s animate our components by the following codes:

<SafeAreaView style={styles.saveArea}>
  <Animated.ScrollView
    contentContainerStyle={{ paddingTop: HEADER_MAX_HEIGHT - 32 }}
    scrollEventThrottle={16} // 
    onScroll={Animated.event(
      [{ nativeEvent: { contentOffset: { y: scrollY } } }], // event.nativeEvent.contentOffset.x to scrollX
      { useNativeDriver: true }, // use native driver for animation
    )}>
    {DATA.map(renderListItem)}
  </Animated.ScrollView>
  <Animated.View
    style={[styles.header, { transform: [{ translateY: headerTranslateY }] }]}>
    <Animated.Image
      style={[
        styles.headerBackground,
        {
          opacity: imageOpacity,
          transform: [{ translateY: imageTranslateY }],
        },
      ]}
      source={require('./assets/management.jpg')}
    />
  </Animated.View>
  <Animated.View
    style={[
      styles.topBar,
      {
        transform: [{ scale: titleScale }, { translateY: titleTranslateY }],
      },
    ]}>
    <Text style={styles.title}>Management</Text>
  </Animated.View>
</SafeAreaView>

Article on Medium

React Native Scrollable Animated Header

How to contribute?

  1. Fork this repo
  2. Clone your fork
  3. Code 🤓
  4. Test your changes
  5. Submit a PR!

More Repositories

1

google-place-autocomplete

🏆 Best practice with Google Place Autocomplete API on React
JavaScript
73
star
2

Gapur

Hi there 🖖, This is my Github README.
33
star
3

react-native-twilio-chat

💬 Build a Twilio-Powered Chat App Using React Native
JavaScript
25
star
4

firebase-push-notifications

📬 Push Notifications With React And Firebase
JavaScript
18
star
5

react-native-vision-camera-examples

📷 React Native VisionCamera and camera library alternatives
Java
15
star
6

react-native-accordion

Animated accordion component for React Native
Java
15
star
7

js-algorithms

🤓 Algorithms and data structures in JavaScript
JavaScript
11
star
8

twilio-paste-intellisense

Intelligent Twilio Paste Design tooling for VS Code
TypeScript
10
star
9

react-native-image-avatar-picker

Using React-Native-Image-Picker
Java
9
star
10

cupido-bot

🤖 Love Calculator Telegram Bot with Node.js
JavaScript
9
star
11

nestjs-microservices

🛰️ Building Microservices with NestJS, TCP and Typescript
TypeScript
9
star
12

nest-chat-app

💬 Build a Real-time Chat App Using NestJS
JavaScript
9
star
13

react-native-dot-typing

💬 React Native Dot Typing Animation Component
Java
6
star
14

github-repository-contributors

✨ How to Add Github Contributors to README ✨
5
star
15

react-native-carousel

🤠 Responsive Horizontal Carousel on React-Native
JavaScript
5
star
16

sheshim

Sheshim is a question and answer site for professional and enthusiast users.
TypeScript
5
star
17

react-native-pressable-example

Why Should We Use Pressable In React Native? 🤔
Java
4
star
18

react-native-scanner

Intro to React Native Camera
Java
4
star
19

react-space

Build a Power 3D Animation with React
JavaScript
3
star
20

react-query-todo-example

🤖 Deep dive into mutations in React Query
TypeScript
3
star
21

react-native-image-detector

React Native Vision Camera and camera library alternatives
Java
3
star
22

ethereum-todo-board

Blockchain Todo Board Web App Powered by Ethereum Smart Contracts
JavaScript
2
star
23

Store

Web app for creating, editing and managing your online store.
JavaScript
2
star
24

place-management

Admin Dashboard Web App
JavaScript
2
star
25

react-native-list

Startup-Namer App on React Native Javascript
Objective-C
1
star
26

react-auto-animate

Animate your components using AutoAnimate with one line 🪄
JavaScript
1
star
27

webpack-tutorial

Configure web app on Webpack 4
JavaScript
1
star
28

baking_mobile

Mobile app for search and cooking baking. Create, edit and delete recipes for different dishes.
JavaScript
1
star