Search code examples
reactjsreact-nativerefuse-ref

Send ref via props in functional component


In my parent component I call hook useRef: const flatListRef = useRef(null); and then I want to use this flatListRef in child component. I tried to do like in documentation but without success. When I call my function toTop I get: null is not an object (evaluating 'flatListRef.current.scrollToOffset')

This is my parent component:

const BeautifulPlacesCards = ({navigation}: HomeNavigationProps<"BeautifulPlacesCards">) => {
    const flatListRef = useRef(null);
    const toTop = () => {
        flatListRef.current.scrollToOffset(1)
    }
    const buttonPressed = () => {
     toTop()
    }
    return(
           <Carousel filteredData={filteredData} flatListRef={flatListRef}/>
    )
}

This is my child component:

const Carousel = forwardRef((filteredData, flatListRef) => {
 return (
         <AnimatedFlatList 
                  ref={flatListRef}
         />
 )
}


Solution

  • Here is a working example: https://snack.expo.dev/@zvona/forwardref-example

    Key takes:

    • you need to use prop ref when passing it down, not flatListRef
    • you need to destructure filteredData from props

    Here is the relevant code:

    const Child = forwardRef(({ filteredData }, ref) => {
      return (
        <FlatList
          ref={ref}
          style={styles.flatList}
          data={filteredData}
          renderItem={({ item }) => (
            <Text style={styles.item} key={`foo-${item}`}>
              {item}
            </Text>
          )}
        />
      );
    });
    
    const App = () => {
      const flatListRef = useRef(null);
    
      const toTop = () => {
        flatListRef.current.scrollToOffset(1);
      };
    
      return (
        <View style={styles.container}>
          <Button title={'Scroll back'} onPress={toTop} />
          <Child filteredData={[1,2,3,4,5,6]} ref={flatListRef} />
        </View>
      );
    };