Issues mapping within a map - React Native

Viewed 37

The app I'm making develops the following array format to store user input:

[
  {name: Bob,
   id: 1,
   sports: [{sport: Baseball,
             id: 1
            },
            {sport: Basketball,
             id: 2
            }]
  },
  {name: James,
   id: 2,
   sports: [{sport: Hockey,
             id: 3
            },
            {sport: Soccer,
             id: 4
            }]
  }
]

I am trying to render this to effectively get the following output:

<Text>Bob</Text>
<Text>Baseball</Text>
<Text>Basketball</Text>

<Text>James</Text>
<Text>Hockey</Text>
<Text>Soccer</Text>

I would of thought I could achieve this by mapping within a map eg:

{Array.map((item) => {
  return(
    <Text>{item.name}</Text>
    {item.sports.map((item2) => {
      return(
        <Text>{item2.sport}</Text>
      )
    })
  )
})}

but can't get anything like this to work. I can console.log the results I want with:

    const display = Array.map(item => {
        return console.log(item.name, item.sports.map(item2 => {
            return item2.sport}))
        })

But I guess I don't know how to render this out?

2 Answers

You have a lot of errors in the code or is it a neglect of responders.

const userInput = [
  {
    name: "Bob",
    id: 1,
    sports: [
      { sport: "Baseball", id: 1 },
      { sport: "Basketball", id: 2 },
    ],
  },
  {
    name: "James",
    id: 2,
    sports: [
      { sport: "Hockey", id: 3 },
      { sport: "Soccer", id: 4 },
    ],
  },
];

{userInput.map((user) => (
  <>
    <Text>{user.name}</Text>
    {user.sports.map((s) => (
      <Text>{s.sport}</Text>
    ))}
  </>
))}

Ok so I just found out what I was doing wrong haha. I need to have the content from my first map and the second map function encased in one View. Eg:

    const display = Array.map(item => {
        return (
            <View>     <------------------------I didn't have these originally
                <View>
                    <Text>
                        {item.name}
                    </Text>
                </View>
                {item.sports.map(item2 => {
                    console.log(item2)
                    return (
                        <View>
                            <Text>
                                {item2.sport}
                            </Text>
                        </View>
                    )
                })}
            </View>     <------------------------I didn't have these originally
        )
    })
Related