3

I need to show an array and I need to render it using array.map not Flatlist because of the orientation issue.

In Flatlist, I can do it easily using numColumns = {2} but I really need to do that using array.map, not Flatlist, I can render the array to show just one column, and that's how I made it:

import React from 'react';
import {View, Text, StyleSheet} from 'react-native';
import {ScrollView} from 'react-native-gesture-handler';

const data = [
  {
    id: 1,
    name: 'Ronaldo',
  },
  {
    id: 2,
    name: 'Ronaldo',
  },
  {
    id: 3,
    name: 'Ronaldo',
  },
  {
    id: 4,
    name: 'Ronaldo',
  },
  {
    id: 5,
    name: 'Ronaldo',
  },
];

const Card = ({id, name}: any) => {
  return (
    <View style={styles.card}>
      <Text>{id}</Text>
      <Text>{name}</Text>
    </View>
  );
};

export default function ColumnsInMap() {
  return (
    <ScrollView>
      {data.map((item, index) => {
        console.log(index);

        return <Card key={index} id={item.id} name={item.name} />;
      })}
    </ScrollView>
  );
}

const styles = StyleSheet.create({
  card: {
    backgroundColor: 'dodgerblue',
    height: 200,
    width: '40%',
    justifyContent: 'center',
    alignItems: 'center',
    margin: 20,
  },
});
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459

1 Answers1

7

you can use flexWrap: 'wrap' and item width 50%

<ScrollView 
    contentContainerStyle={{
        flexDirection: 'row',
        flexWrap: 'wrap'
    }}>

     <View style={{width : '50%'}}></View>
     <View style={{width : '50%'}}></View>
     ....

</ScrollView>

your example try snack here.

import React from 'react';
import {View, Text, StyleSheet, ScrollView} from 'react-native';

const data = [
  {
    id: 1,
    name: 'Ronaldo',
  },
  {
    id: 2,
    name: 'Ronaldo',
  },
  {
    id: 3,
    name: 'Ronaldo',
  },
  {
    id: 4,
    name: 'Ronaldo',
  },
  {
    id: 5,
    name: 'Ronaldo',
  },
];

const Card = ({id, name}: any) => {
  return (
    <View style={styles.card}>
      <Text>{id}</Text>
      <Text>{name}</Text>
    </View>
  );
};

export default function ColumnsInMap() {
  return (
    <ScrollView 
    contentContainerStyle={{
        flexDirection: 'row',
        flexWrap: 'wrap'}}
      >
      {data.map((item, index) => {
        console.log(index);

        return (
          <View style={{width : '50%', flexDirection : "row"}}>
            <Card key={index} id={item.id} name={item.name} />
          </View>
        );
      })}
    </ScrollView>
  );
}

const styles = StyleSheet.create({
  card: {
    backgroundColor: 'dodgerblue',
    height: 200,
    flex : 1,
    alignSelf : "center",
    justifyContent: 'center',
    alignItems: 'center',
    margin: 20,
  },
});

the result
enter image description here

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Ahmed Gaber
  • 3,384
  • 2
  • 12
  • 18