Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invariant Violation: Changing numColumns on the fly is not supported. I do not change though [duplicate]

{
   selected.length == 2 
   ?
   <FlatList
   keyExtractor={item => "_" + item.id}
   renderItem={this.renderLastItem}
   data={subGroups}
   numColumns={1} /> 
   :
   <FlatList
   keyExtractor={item => "#" + item.id}
   renderItem={this.renderItem}
   data={subGroups}
   numColumns={2} />
}

In the above lines of code when selected.length equals 2, I get the following error:

Invariant Violation: Changing numColumns on the fly is not supported. 

These are two different lists and I am not changing numColumns. It seems to me that react native is trying to use the same object of FlatList in all conditions. How can I solve this issue ?

like image 627
a.toraby Avatar asked Aug 15 '20 09:08

a.toraby


1 Answers

This question has been asked and answered here. I am not sure exactly why this error is thrown. But with all the optimizations around rendering that are implemented on FlatList, it might have been a decision taken by RN team to throw this error.

As described in the answer to linked question, you'll need to add keys to the FlatList in order to help React-Native refresh the component on selected value change.

You can fix it by doing

{selected.length == 2 ?
<FlatList
   key={'_'}
   keyExtractor={item => "_" + item.id}
   renderItem={this.renderLastItem}
   data={subGroups}
   numColumns={1} /> 
   :
<FlatList
   key={'#'}
   keyExtractor={item => "#" + item.id}
   renderItem={this.renderItem}
   data={subGroups}
   numColumns={2} />
}

Github issue raised similar to this https://github.com/facebook/react-native/issues/15944

like image 101
Nishant Nair Avatar answered Oct 16 '22 14:10

Nishant Nair