3

I'm trying to pass a ref to a component with a similar approach to the following code block, but the current value always returns undefined. This approach works fine with a plain FlatList from react-native, however it doesn't work once I'm using either an Animated.FlatList or an Animated.createAnimatedComponent(FlatList) :

const Parent = () => {
    const flatListRef = useRef();

    useEffect(() => {
        console.log(flatListRef.current) // undefined
    })

    return (
        <View>
            <Child ref={flatListRef} />
        </View>
    )
}

const Child = React.forwardRef((props, ref) => {

    return (
        <Animated.FlatList
            ref={ref}
        />
    )
})
IronManAYaad
  • 143
  • 2
  • 7

1 Answers1

3

The library react-native-reanimated works a little bit different in comparison to react-native-animated.

If we create the animated component via Animated.createAnimatedComponent(FlatList), then everything works as expected.

Here is a working version of your code. I have logged the function scrollToIndex of the FlatList ref for testing purposes.

import Animated from "react-native-reanimated"

const ReanimatedFlatList = Animated.createAnimatedComponent(FlatList);

const Parent = (props) => {
    const flatListRef = useRef(null);

    useEffect(() => {
      console.log(flatListRef.current.scrollToIndex)
    }, [])

    return (
        <View>
            <Child ref={flatListRef} />
        </View>
    )
}

const Child = React.forwardRef((props, ref) => {
    return (
        <ReanimatedFlatList
            ref={ref}
        />
    )
})
David Scholz
  • 8,421
  • 12
  • 19
  • 34
  • 1
    This works! I appreciate the assistance. Where can I find the differences between `Animated.FlatList` and `Animated.createAnimatedComponent(FlatList)` ? – IronManAYaad Mar 30 '22 at 10:36
  • You are welcome! These are two different libraries. They are implemented by different developers. I am not aware of an official overview on what is different between these two. There might be some blog posts out there which cover this. The react-native-reanimated library is [documented here](https://docs.swmansion.com/react-native-reanimated/docs/). – David Scholz Mar 30 '22 at 10:43
  • `Animated.FlatList` and `Animated.createAnimatedComponent(FlatList)` are both provided by `react-native-reanimated`. The difference in the code is here: https://github.com/software-mansion/react-native-reanimated/blob/2.9.1/src/reanimated2/component/FlatList.tsx. The former is composed by the latter, plus also wraps its cellRenderer in a ReanimatedView. In practice, I don't know how this affects the component – pdpino Jul 27 '22 at 19:11