Muljayan
Muljayan

Reputation: 3886

FlatList items not rerendering when parent props change

I have a component which has a FlatList and props are being passed into it from the parent as follows.

Parent Component

const Parent = (props) => {
  const [currentValue, setCurrentValue] = useState(0);
  // Changes are detected here
  console.log(currentValue)
  return (
    <FlatListContainer
      currentValue={currentValue}
      setCurrentValue={setCurrentValue}
    />
  );
};

FlatListContainer Component

const FlatListContainer = (props) => {
  const { currentValue, setCurrentValue } = props;

  return (
    <FlatList
      data={data}
      keyExtractor={item => `${item.id}`}
      renderItem={({ item, index }) => (
        <OptionItem
          label={item.name}
          value={item.id}
          currentValue={currentValue}
          onPress={setCurrentValue}
        />
      )
      }
    />
  );
};

I have not included how data is retrieved for simplicity sake.

The OptionItem is as follows.

OptionItem Component

const OptionItem = (props) => {
  const { label, onPress, value, currentValue } = props;

  const _onPress = () => {
    onPress(value);
  };

  return (
    <TouchableOpacity
      activeOpacity={0.6}
      onPress={_onPress}
    >
      {/* CONTENT HERE */}
      <Text>{label}</Text>
      {value === currentValue ? 'Selected' : 'Not Selected'}
    </TouchableOpacity>
  );
};

When i console.log(currentValue) inside OptionItem component i dont see the change in value on clicked. How ever the change is detected in the FlatListContainer and the Parent Components.

How do i make the OptionItem component detect this change and change its contents accordingly

Upvotes: 0

Views: 49

Answers (1)

Victor
Victor

Reputation: 4199

Add extraData={currentValue} into the flatlist. Flatlist re-renders only on data change or something in extraData changes.

extraData

A marker property for telling the list to re-render (since it implements PureComponent). If any of your renderItem, Header, Footer, etc. functions depend on anything outside of the data prop, stick it here and treat it immutably.

https://facebook.github.io/react-native/docs/flatlist.html#extraData

Upvotes: 1

Related Questions