Home > database >  How can I pass a ref to a react-native-reanimated component?
How can I pass a ref to a react-native-reanimated component?

Time:03-31

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}
        />
    )
})

CodePudding user response:

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}
        />
    )
})
  • Related