Lorence
Lorence

Reputation: 13

pass state data from child to nested component

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

  <FlatList
    contentContainerStyle={styles.contentContainer}
    ref={flatListRef}
    scrollEnabled
    showsVerticalScrollIndicator={false}
    data={videos}
    onMomentumScrollEnd={(e) => {
      setIndex(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

Upvotes: 1

Views: 43

Answers (1)

Hend El-Sahli
Hend El-Sahli

Reputation: 6742

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

Upvotes: 2

Related Questions