0

I am attempting to map an array of objects (photo details) into a component so that it will line them up in rows with three (3) components in each row (three images).

I have tried creating a nested for loop to have the components print out like I described but to no avail. I am fairly new to React Native, but have been programming in other languages (C, Java, Javascript) for years.

Here is my code thus far:

class PhotoList extends Component {
    render() {
        var payments = [];

        for(let j = 0; j < PHOTO_DATA.length; J++){
            payments.push(
                <View>
            )
            for(let i = 0; i < 3 || j < PHOTO_DATA.length; i++){
                j = j + 1;
                payments.push(
                    <Photo key={i} {...PHOTO_DATA.pop} press={this.props.press} />
                )
            }
            payments.push(
                </View>
            )
        }

        return (
            <View style={photoList.container}>
                <ScrollView>
                    { payments }
                    {/* {PHOTO_DATA.map((item, i) => {
                        return <Photo key={i} {...item} press={this.props.press} />
                    })} */}
                </ScrollView>
            </View>
        )
    }
}

Any help is very much appreciated, thanks!

1 Answers1

0

Problem here is that you are treating JSX the wrong way. JSX tags is not something that you can emit as plain text (like you would emit HTML with PHP). When you buildyour project, this <View a={1} b={2} /> compiles into this React.createElement('View', { a:1, b: 2}) so your code is not a valid JSX

You should use .map for this PHOTO_DATA.map(item => <Photo key={i} /* your other props */ /> this will give you rendered Photo components

Another problem here is that you also want to split items by groups of 3 for the sake of styling. You should be using styles for that, e.g. create a parent View, put all the rendered <Photo />s inside and use flexbox to style your elements accordingly (refer to this answer on how to do that, for example)

But if you still want to know how to do what you did with JSX instead of styles, you would first have to split array in chunks of 3 (here you'd end up with array of arrays of 3 items each), then use .map to render Views with Photos inside, e.g.

return (
    {chunkedArray.map(group =>
      <View>
        {group.map(photo => <Photo />)}
      </View>
    )}
  )
Max
  • 4,473
  • 1
  • 16
  • 18