Areza
Areza

Reputation: 721

react-native: flatlist with dynamic numColumns depending json params

This is my json:

{
   data:[
      {id:1,type:0...},{id:2,type:0...},{id:3,type:1...},
   ]
}

and Flatlist

_keyExtractor = (item,index) => item.id.toString();

<FlatList
   data={this.state.products}
   renderItem={this.renderItem}
   keyExtractor={this._keyExtractor}
   numColumns={3}
/>

I want something like this:

 numColumns={item.type ? 1 : 2}

Is it possible?

Upvotes: 0

Views: 2082

Answers (1)

Tim
Tim

Reputation: 10709

Unfortunately, numColumns sets the number of columns for the global FlatList, but it is possible to create a similar behavior in your renderItem function.

Of course it is possible that you have to modify the structure of your data beforehand, so that this workaround is applicable for you.

See example below:

Data:

  this.state={
            data:[
      {id:1,type:0},{id:2,type:1},{id:3,type:1},
      {id:4,type:0},{id:5,type:1},{id:6,type:0},
   ]
        }

Render:

const WIDTH = Dimensions.get('window').width; // get the screen width 

renderItem({item}){
    // if type == 0, render two views side by side
    if (item.type == 0){
        return(
            <View style={{width: WIDTH, flexDirection: 'row'}}>
                <View style={{ backgroundColor: 'red', width: WIDTH/2 }}>
                    <Text> {item.id} a) </Text>
                </View>
                <View style={{ backgroundColor: 'blue', width: WIDTH/2 }}>
                    <Text> {item.id} b) </Text>
                </View>
            </View>
        );
    }else{
        // otherwise render only one item 
        return (
            <View style={{ backgroundColor: 'green', width: WIDTH }}>
                <Text> {item.id} </Text>
            </View>
        );
    } 
}
render() {
    return (
        <SafeAreaView style={styles.container}>
            <FlatList
            data={this.state.data}
            keyExtractor={(item) => item.id.toString()}
            renderItem={(item) => this.renderItem(item)}
            />
        </SafeAreaView>
    );
}

Image:

Image example

Upvotes: 2

Related Questions