react-native-reanimated: `useAnimatedStyle` causing focus and button press issues in `FlatList`

Description

I am encountering a problem when using animations with FlatList. Specifically, when I use Animated or useAnimatedStyle from Reanimated for tab animations, the following issues occur:

The TextInput in the second tab (and onwards) doesn’t gain focus when tapped. Any TouchableOpacity or button inside the FlatList items also becomes unresponsive. When I switched from Reanimated’s useAnimatedStyle to Animated from React Native, the issue was resolved, and everything worked as expected. This appears to be a problem with how useAnimatedStyle interacts with FlatList.

Steps to reproduce

Copy the code below into a fresh React Native project. Run the app. Try focusing on the TextInput in the second tab or pressing any button inside the second tab. Comment out Reanimated usage and use React Native’s Animated instead to observe the difference.

import React, { useState, useRef } from 'react';
import {
  View,
  TextInput,
  FlatList,
  StyleSheet,
  Dimensions,
  Animated,
  TouchableOpacity,
} from 'react-native';
import { Box, Typography } from '@shopify/restyle';

const { width } = Dimensions.get('window');
const spacing = 16;

type TabData = {
  id: number;
  title: string;
  placeholder: string;
};

const CustomTabView = () => {
  const [tabsData] = useState<TabData[]>([
    { id: 1, title: 'Tab 1', placeholder: 'Enter text for Tab 1' },
    { id: 2, title: 'Tab 2', placeholder: 'Enter text for Tab 2' },
    { id: 3, title: 'Tab 3', placeholder: 'Enter text for Tab 3' },
  ]);

  const [tabValues, setTabValues] = useState<{ [key: number]: string }>({
    1: '',
    2: '',
    3: '',
  });

  const [activeTab, setActiveTab] = useState(0);
  const flatListRef = useRef<FlatList>(null);
  const animatedIndicator = useRef(new Animated.Value(0)).current;

  const handleTabPress = (index: number) => {
    setActiveTab(index);

    // Animate the indicator to the selected tab
    Animated.timing(animatedIndicator, {
      toValue: index * (width / tabsData.length),
      duration: 250,
      useNativeDriver: false,
    }).start();

    flatListRef.current?.scrollToIndex({
      animated: true,
      index,
    });
  };

  const handleInputChange = (id: number, value: string) => {
    setTabValues((prevState) => ({ ...prevState, [id]: value }));
  };

  return (
    <View style={styles.container}>
      {/* Tab Buttons with Animated Indicator */}
      <Box
        flexDirection="row"
        justifyContent="space-around"
        bg="gray200"
        position="absolute"
        width={width - spacing}
        top={0}
        zIndex={1}
        borderRadius="s"
        overflow="hidden"
        style={{
          padding: spacing / 3,
          marginHorizontal: spacing / 2,
        }}
      >
        <Animated.View
          style={[
            styles.indicator,
            {
              width: width / tabsData.length,
              transform: [{ translateX: animatedIndicator }],
            },
          ]}
        />
        {tabsData.map((tab, index) => (
          <TouchableOpacity
            key={index}
            style={styles.tabButton}
            onPress={() => handleTabPress(index)}
          >
            <Typography
              textAlign="center"
              fontFamily="medium"
              color={activeTab === index ? 'globalWhite' : 'textSecondary'}
            >
              {tab.title}
            </Typography>
          </TouchableOpacity>
        ))}
      </Box>

      {/* Content for Each Tab */}
      <FlatList
        ref={flatListRef}
        data={tabsData}
        renderItem={({ item }) => (
          <View style={styles.tabContainer} key={item.id}>
            <TextInput
              style={styles.textInput}
              placeholder={item.placeholder}
              value={tabValues[item.id]}
              onChangeText={(text) => handleInputChange(item.id, text)}
              onFocus={() => console.log(`Focused on Tab ${item.id}`)}
            />
          </View>
        )}
        keyExtractor={(item) => item.id.toString()}
        horizontal
        showsHorizontalScrollIndicator={false}
        pagingEnabled
        keyboardShouldPersistTaps="always"
        removeClippedSubviews={false} // Important to ensure inputs offscreen remain interactive
        onMomentumScrollEnd={(event) => {
          const index = Math.floor(event.nativeEvent.contentOffset.x / width);
          setActiveTab(index);
          Animated.timing(animatedIndicator, {
            toValue: index * (width / tabsData.length),
            duration: 250,
            useNativeDriver: false,
          }).start();
        }}
      />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    marginTop: 100, // Space for tab bar at the top
  },
  tabContainer: {
    width,
    justifyContent: 'center',
    alignItems: 'center',
  },
  textInput: {
    width: '80%',
    borderColor: '#ccc',
    borderWidth: 1,
    padding: 10,
    borderRadius: 5,
  },
  tabButton: {
    flex: 1,
    alignItems: 'center',
  },
  indicator: {
    position: 'absolute',
    top: 0,
    bottom: 0,
    backgroundColor: 'blue',
    borderRadius: 10,
  },
});

export default CustomTabView;

Snack or a link to a repository

https://snack.expo.dev/_cgYFhPQvKDe1htoimwii

Reanimated version

3.16.1

React Native version

0.76

Platforms

Android

JavaScript runtime

None

Workflow

None

Architecture

None

Build type

None

Device

None

Device model

No response

Acknowledgements

Yes

About this issue

  • Original URL
  • State: open
  • Created 2 years ago
  • Reactions: 3
  • Comments: 15 (3 by maintainers)

Most upvoted comments

I found the problem. The animation caused the click event of the internal element of Animated.View to be abnormal.

Encapsulates a hook to obtain the translate style of the current panel

import { useEffect } from 'react';
import {
  Easing,
  WithTimingConfig,
  useAnimatedStyle,
  useSharedValue,
  withTiming,
} from 'react-native-reanimated';

const DEFAULT_TIME_CONFIG: WithTimingConfig = {
  duration: 300,
  easing: Easing.out(Easing.ease),
};

export default function useTranslateY(
  visible?: boolean,
  options?: {
    timeConfig?: WithTimingConfig;
    onComplete?: (value: number) => void;
  },
) {
  const translateY = useSharedValue(100);
  const timeConfig = options?.timeConfig || DEFAULT_TIME_CONFIG;

  useEffect(() => {
    if (visible) {
      translateY.value = withTiming(0, timeConfig, () =>
        options?.onComplete?.(0),
      );
    } else {
      translateY.value = withTiming(100, timeConfig, () =>
        options?.onComplete?.(100),
      );
    }
  }, [options, timeConfig, translateY, visible]);

  const animatedTranslateY = useAnimatedStyle(() => ({
    transform: [{ translateY: `${translateY.value}%` }], //  effect press event, all of press event and touch event dont work, event animation done
    // transform: [{ translateY: visible ? 0 : `${translateY.value}%` }],    // it work without animation
  }));

  return animatedTranslateY;
}

In Android, the Panel child elements cannot trigger press and touch events normally, but there seems to be no problem in iOS.

const PanelBase: React.FC<PropsWithChildren<IPanelBaseProps>> = ({
  visible,
  maxHeightPercent = 0.7,
  minHeightPercent = 0.3,
  children,
  containerStyle,
  ...modalBaseProps
}) => {
  const insets = useSafeAreaInsets();
  const animatedTranslateY = useTranslateY(visible);

  const heightStyle = useMemo(() => {
    let maxHeight = SCREEN_HEIGHT * maxHeightPercent + insets.bottom;
    if (maxHeight > SCREEN_HEIGHT) {
      maxHeight = SCREEN_HEIGHT;
    }
    let minHeight = SCREEN_HEIGHT * minHeightPercent + insets.bottom;
    if (minHeight > SCREEN_HEIGHT) {
      minHeight = SCREEN_HEIGHT;
    }
    if (minHeight > maxHeight) {
      minHeight = maxHeight;
    }
    return { maxHeight, minHeight };
  }, [insets.bottom, maxHeightPercent, minHeightPercent]);

  return (
    <ModalBase visible={visible} {...modalBaseProps}>
      <Animated.View style={[styles.content, animatedTranslateY]}>
        <View
          style={[
            heightStyle,
            { paddingBottom: insets.bottom || px2dp(16) },
            containerStyle,
          ]}>
          {children}
        </View>
      </Animated.View>
    </ModalBase>
  );
};