Search code examples
react-nativelistviewfrontendrenderingreact-native-flatlist

React Native Flatlist numColumns is not making multiple columns


I have just started to learn React Native, and this is my first project - a news app. However, I have successfully rendered the image and description of the news using React Native Flatlist.

But when I am using numColumns for making two columns, the column number remains the same. But the number of the shown images becomes the half (i.e. from 18 to 9 in my case). And also the description of the image is going under the image of the next news like shown below -

      

My source code looks like below -

import React, { Component } from 'react'
import { View, Text, FlatList, TouchableHighlight, SectionList, TouchableOpacity , Image,StyleSheet } from 'react-native'
import { ScrollView } from 'react-native-gesture-handler';
import { HomeNewsJSON } from "../../../../assects/JSON/Home"

class HomeNews extends Component {
  constructor(props) {
    super(props);
    this.state = {
      news: ""
    };
  }

  componentDidMount() {
    this.getInfo();
  }

  getInfo() {
    var data = []
    var jsondata = HomeNewsJSON["items"]
    // alert(jsondata.length)
    this.setState({
      news: jsondata
    })
  }
  renderImage(item) {
    var a = item;
    return (
        <TouchableOpacity  
                 style={{flex:1/3,
                 aspectRatio:1}}>
                <Image style={{flex: 1}} resizeMode='cover' source={{ uri:  (a.slice(a.indexOf("src") + 5, a.indexOf("</a>") - 3))}}></Image>
        </TouchableOpacity>
    )
}
  renderPic(data) {
    var a = data;
    return (a.slice(a.indexOf("src") + 5, a.indexOf("</a>") - 3));
  }

  render() {
    var result = Object.entries(this.state.news);
    console.log(result)
    return (
      <View>
        <FlatList
          contentContainerStyle={{margin:2}}
          style={{borderWidth: 0}}
          horizontal={false}
          numColumns={2}
          keyExtractor={item => item.findIndex}
          data={result}
          renderItem={({ item }) => (
            <View>
              {this.renderImage(item[1]["description"])}
              <Text>{item[1]["description"]}</Text>
            </View>
          )}
        />
      </View>
    )
  }
}

export default HomeNews

Please, anyone, suggest me a way to fix it. I really appreciate any help you can provide.


Solution

  • try flex:1 with View outside of item

      renderItem={({ item }) => (
         <View
                style={{
                  flex: 1,
                  flexDirection: 'column',
                }}>
               //image here
              </View>
    )