Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native: Array.map not rendering within Scrollview

I'm trying to render a list of items within a ScrollView Component from an array of data, but for some reason the items are not showing up, or perhaps rendering at all!? From the example below, only <SomeOtherComponent /> shows up, when there should be three orange squares before it (assuming this.state.test is an array of, say, [0, 1, 2]). What am I doing wrong?

<ScrollView
  style={{flex: 1}}
  contentContainerStyle={{width: '100%', alignItems: 'center'}}>
  
  {this.state.test.map((item, index) => {
    <View style={{height: 50, width: 50, backgroundColor: 'orange', marginBottom: 10}} />
  })}
  
  <SomeOtherComponent />
</ScrollView>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
like image 278
swimisbell Avatar asked Aug 15 '17 22:08

swimisbell


3 Answers

You need to return each mapping!

  {this.state.test.map((item, index) => {
        return (
            <View style={{height: 50, width: 50, backgroundColor: 'orange', marginBottom: 10}} />
        )
  })}
like image 147
wnamen Avatar answered Nov 18 '22 17:11

wnamen


You are not returning anything in your map function. => {} suggests a function.

Use => {return <Component/>} or => <Component/>

like image 5
joeydebreuk Avatar answered Nov 18 '22 16:11

joeydebreuk


You need to return the component inside map you can do as @wnaman says in the other answer or you can just remove the { } braces and it will return as expected.

  {this.state.test.map((item, index) => 
    <View style={{height: 50, width: 50, backgroundColor: 'orange', marginBottom: 10}} />
  )}
like image 5
Purgatory Avatar answered Nov 18 '22 15:11

Purgatory