johanjohansson
johanjohansson

Reputation: 541

How do I properly map array into <Text> (React native)

I have an array that I need to map out in <Text>. This is what I've got in render()

categories.map(category => <Text>{category.testHeader}</Text>

But it doesn't print anything. I guess <Text> needs to be in render() right? So I tried adding it in a function to be called in render. Like this:

function myfunc() {
    return categories.map(category => <Text>{category.testHeader}</Text>)
}

Then in render():

<View>
    {myfunc()}
</View>

But then the compiler said `Cannot read property 'map' of undefined. SO tips told me to put write:

function myfunc() {
    if (this.props.data) {
        return categories.map(category => <Text>{category.testHeader}</Text>)
    }
}

But now the compiler tells me that data is undefined. Not sure what to do here... :/

Upvotes: 2

Views: 10137

Answers (2)

Developer Live
Developer Live

Reputation: 62

Firstly defined the data to be []. Then assign categories array to data and try to use it. If required use JSON.parse(data)

Upvotes: 0

erkan
erkan

Reputation: 242

You can use like this:

var categories = [{ id: 0, text: 'hasan' }, 
    { id: 1, text: 'erkan' },
    { id: 2, text: 'veli' }];

export default class App extends Component {
renderCategories() {
    return categories.map((item, index) => <Text key={index}>{item.text}</Text>);
}
render() {
    return (
        <View style={styles.container}>
            {this.renderCategories()}
        </View>
    );
}

}

Upvotes: 7

Related Questions