fun joker
fun joker

Reputation: 1727

How can I display array elements passed as a prop to functional component?

I have created amenitiesArray which has elements like club_house, swimming_pool, etc. I am mapping over this amenitiesArray using .map() but when I pass it as a prop I am not able to display it on screen why so?

console.log(amenitiesArray) is:

0:"Gymnasium"
1:"swimming_pool"
2:"club_house"
3:"childrens_play_area"
4:"multipurpose_room"
5:"security"
6:"jogging_track"
7:"power_backup"
8:"landscaped_gardens"
9:"car_parking"

Code:

const DisplayAmenities = ({ name }) => (
  <Text style={{ color: 'black', fontSize: 16 }}>{name}</Text>
);

export default class Project extends Component {
  render() {
    let amenitiesArray = [];

    for (var key in amenities[0]) {
      if (amenities[0][key] === 'Yes') {
        amenitiesArray.push(key);
      }
    }
    console.log(amenitiesArray);

    return (
      <ScrollView>
        <View style={{ marginTop: 20 }}>
          {amenitiesArray.map(val => {
            <DisplayAmenities name={val} />;
          })}
        </View>
      </ScrollView>
    );
  }
}

Above code does not display anything on screen? Why so?

Upvotes: 0

Views: 35

Answers (2)

Tu Nguyen
Tu Nguyen

Reputation: 10179

Because you forgot to return the component. Try to fix like this:

 return (
      <ScrollView>
        <View style={{ marginTop: 20 }}>
          {amenitiesArray.map((val,index) => {
            return <DisplayAmenities key={index} name={val} />;  //fixed
          })}
        </View>
      </ScrollView>
    );

For short, you could omit the curly brackets, like so

 return (
      <ScrollView>
        <View style={{ marginTop: 20 }}>
          {amenitiesArray.map((val,index) => <DisplayAmenities key={index} name={val} /> )}
        </View>
      </ScrollView>
    );

Upvotes: 2

Estus Flask
Estus Flask

Reputation: 222503

  {amenitiesArray.map(val => {
    <DisplayAmenities name={val} />;
  })}

lacks explicit return, map callback function maps an array to an array of undefined.

For implicit arrow return, it should be:

  {amenitiesArray.map(val => 
    <DisplayAmenities name={val} />;
  )}

The use of array-callback-return ESLint rule allows to avoid this sort of mistakes.

Upvotes: 1

Related Questions