Home > Software engineering >  pass state data from child to nested component
pass state data from child to nested component

Time:11-23

const Child =({ChildIndex})=>{
const [index, setIndex] = useState()

    <FlatList
      contentContainerStyle={styles.contentContainer}
      ref={flatListRef}
      scrollEnabled
      showsVerticalScrollIndicator={false}
      data={videos}
      onMomentumScrollEnd={e => {
      ChildIndex(Math.round(e.nativeEvent.contentOffset.x / width));
    }} 
    onEndReachedThreshold={Platform.OS === 'ios' ? 0 : 1}
    />
/>
}

const Parent =()=>{
const [currentChildIndex, setCurrentChildIndex] = useState()
<Child 
ChildIndex={ChildIndex}
/>
}

I wanted to get the updated currentchildindex, in the parent component. It shows the index when it first loads but it doesn't update afterward. Tried to look useState hook but not luck

CodePudding user response:

You just need to pass setCurrentChildIndex instead:

const Parent = () => {
  const [currentChildIndex, setCurrentChildIndex] = useState();
  useEffect(() => {
    console.log("CurrentChildIndex has been updated", currentChildIndex);
  }, [currentChildIndex]);
  return <Child setCurrentChildIndex={setCurrentChildIndex} />;
};

and consume it in your Child component instead of setIndex

const Child =({setCurrentChildIndex})=>{


    <FlatList
      contentContainerStyle={styles.contentContainer}
      ref={flatListRef}
      scrollEnabled
      showsVerticalScrollIndicator={false}
      data={videos}
      onMomentumScrollEnd={e => {
      setCurrentChildIndex(Math.round(e.nativeEvent.contentOffset.x / width));
    }} 
    onEndReachedThreshold={Platform.OS === 'ios' ? 0 : 1}
    />
/>
}
  • Related