Search code examples
reactjsreact-nativereact-animated

Background color opacity interpolation not working


I want to make the custom header going from transparent to opaque on vertical scroll (start when scrollY reaches 150 and make fully opaque at 250). I have the following code, but the opacity doesn't update, and I can't figure out why:

import React from 'react';
import { StyleSheet, Animated } from 'react-native';

export default function App() {
    const scrollY = React.useRef(new Animated.Value(0)).current;

    const opacity = scrollY.interpolate({
        inputRange: [0, 150, 250],
        outputRange: [0, 0, 1],
        extrapolate: 'clamp'
    });

    return (
        // Header
        <Animated.View
            style={{
                ...styles.header,
                backgroundColor: `rgba(255, 255, 255, ${opacity})`
            }}
        >
                /* some content */
        </Animated.View>

        // Vertical list
        <Animated.FlatList
            onScroll={Animated.event(
                [{ nativeEvent: { contentOffset: { y: scrollY } } }],
                { useNativeDriver: false }
            )}
            data={DATA}
            keyExtractor={(item, index) => index.toString()}
            renderItem={renderItem}
            ListHeaderComponent={ListHeader}
        />
    );
}

Solution

  • You can interpolate backgroundColor directly.

    const backgroundColor = animValue.interpolate({
        inputRange: [0, 150, 250],
        outputRange: ['#00000000', '#00000000', '#FFF'], // You can play around it
        extrapolate: 'clamp'
    })
    
    ...
    
    <Animated.View
        style={{
            ...styles.header,
            backgroundColor
        >