Vipul Tyagi
Vipul Tyagi

Reputation: 667

Cannot render array elements using map in react native

I have below react-native code that I am using to render a text of array elements using map.

import React from 'react';
import { createStackNavigator } from '@react-navigation/stack';
import {Card} from 'react-native-elements';
import {View, Text} from 'react-native';


class Contact extends React.Component{
    constructor(props){
        super(props);
        this.state={
            arr:["Vipul","Satish","Manisha","Jonty"]
        }
    }
    render(){
        return(
            <Card>
                <Card.Title>Contact Information</Card.Title>
                <Card.Divider />
                <View>
                    {
                        this.state.arr.map(function(elem){
                            console.log(elem)
                            return(
                                <Text>Hello {elem}</Text>
                            );
                        })
                    }
                </View>
            </Card>
        );
    }
}

export default Contact;

I already have array setup with state in constructor of my class. First I was using arrow function to return <Text>. But it wasn't working. Now regular function isn't working too. I am getting below error:

Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined.

However, If I replace my render function with this:

render(){
   return(<View><Text>Hello world</Text></View>);
}

then everything is working fine and I am getting Hello world on screen. Also, the console.log in the above code is correctly printing all the array elements but it is just that the elements are not being rendered.

I have checked other topics similar to this but couldn't get any help.

Thank You! The state is this:

constructor(props){
        super(props);
        this.state={
            arr:["Vipul","Satish","Manisha","Jonty"]
        }
    }

EDIT: This is what has been given on their official website:

<Card>
  <Card.Title>CARD WITH DIVIDER</Card.Title>
  <Card.Divider/>
  {
    users.map((u, i) => {
      return (
        <View key={i} style={styles.user}>
          <Image
            style={styles.image}
            resizeMode="cover"
            source={{ uri: u.avatar }}
          />
          <Text style={styles.name}>{u.name}</Text>
        </View>
      );
    })
  }
</Card>

You can see that my code is just similar to this one, so it should work that way.

Upvotes: 1

Views: 147

Answers (1)

Eric Hasselbring
Eric Hasselbring

Reputation: 1424

not sure what lib you are using for Card but it may take a title prop not a string as a child.

Upvotes: 1

Related Questions