React Native multiple ref not working in Flatlist

I coding an infinity list.

Each item of the list consists of a video.

Components:

Parent Component

import React, { useState, useEffect, useRef } from 'react';

import { View,FlatList, } from 'react-native';

export default function Parent() {
  const [list, setList] = useState([]);
  const cellRefs = useRef({});

  const _getData = () => {
   
    const reponse = _createData();

    setList(reponse)
  };


  useEffect(() => {
    _getData();
  }, []);

  const _onViewableItemsChanged = React.useRef(({ changed }) => {

    changed.forEach((item) => {

      const cell = cellRefs.current[item.key];  

      console.log('cell', cell); // return undefined 

      if (cell) {

        if (item.isViewable) {

          cell.play();

        } else {

          cell.pause();

        }
      }
    });
  });

  const viewConfigRef = React.useRef({ viewAreaCoveragePercentThreshold: 50 });


 return (
      <FlatList
        data={list} 
          
        onViewableItemsChanged={_onViewableItemsChanged.current}

        viewabilityConfig={viewConfigRef.current}   
    
        keyExtractor={(item) => item.id.toString()}
       
         // Something

        renderItem={({ item }) => (
          <Post
            item={item}

            ref={cellRefs.current[item.id]}  
    
          />
        )}
      />
  );

 }

**Child Component **

import React, { useRef, useEffect } from 'react';

import { View } from 'react-native';

import { Video, } from 'expo-av';

export default function Post() {

  const video = useRef(null).current;
  
  useEffect(() => {

    return () => {

      if (video?.unLoad !== undefined) {

        const unLoad = async () => {
          await video.unloadAsync();
        };

        unLoad();
      }
    };
  }, []);

  const play = async () => {

    console.log('play');

    const status = await video.getStatusAsync();

    if (status.isPlaying) {
      return;
    }

    await video.playAsync();
  };

  const pause = async () => {

    if (video) {

      await video.stopAsync();

    }
  };

  return (
    <View style={Styles.root}>

      <Video
        ref={video}

        style={Styles.video}
        source={{
          uri: '....',
        }}
        audioOnly
        resizeMode="contain"    
        shouldPlay={false}
      />
    </View>
  );
}

I can’t access the function of child component.

(cellRefs.current is undefined)

Thanks for helping

1 Like

I solved it using useImperativeHandle and forwardRef in ChildComponent.

This topic was automatically closed 20 days after the last reply. New replies are no longer allowed.