简体   繁体   中英

Render multiple JSX elements from object array

I am having trouble generating multiple JSX elements eg(multiple text fields or buttons from the data I map from the object arrays) It generates all of the array content within one JSX tag / element. How could I get it to generate multiple tags? Thank you in advance.

const labourers = [
  {
    id: 1,
    name: 'Velry Mokwena',
    skills: ['Domestic Cleaning'],
    location: ['Pretoria'],
    rating: 100,
  },
  {
    id: 2,
    name: 'Isaac Cindi',
    skills: ['Gardening', 'Painting', 'Plastering', 'General Labour'],
    location: ['Centurion'],
    rating: 100,
  },
  {
    id: 3,
    name: 'Joseph Mahlangu',
    skills: ['Bricklaying', 'Plastering'],
    location: ['Menlo Park', 'Pretoria'],
    rating: 100,
  },
];

var labourer = labourers.map(labourer => (
  <View key={labourer.id} style={{display: 'flex', marginBottom: 20, backgroundColor: 'gray', padding: 20}}>
    <Text style={{textAlign: 'center'}}>{labourer.name}</Text>
    <Text style={{textAlign: 'center'}}>{labourer.skills}</Text>
    <TouchableOpacity><Text style={{textAlign: 'center'}}>{labourer.location}</Text></TouchableOpacity>
  </View>
));

Instead of this

 <Text style={{textAlign: 'center'}}>{labourer.skills}</Text>

Which will join the array to a single text string, just map it to another jsx element instead:

{labourer.skills.map(skill => 
 <Text style={{textAlign: 'center'}}>{skill}</Text>
)}

You need some modification in iteration logic as below

render(){
.
.
.
          var labourer = labourers.map(function(labourer){
                  return(  <View key={labourer.id} style={{display: 'flex',marginBottom: 20, backgroundColor: 'gray', padding: 20}}>
                             <Text style={{textAlign: 'center'}}>{labourer.name}</Text>
                             <Text style={{textAlign: 'center'}}>{labourer.skills}</Text>
                             <TouchableOpacity><Text style={{textAlign: 'center'}}>{labourer.location}</Text></TouchableOpacity>
                            </View> )
         });

         return (
                //render here
                <div>
                  labourer
                </div>

         )
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM