Search code examples
javascriptreact-nativereact-native-flatlistnested-object

React Native Flatlist - How to loop through nested object


I have a JSON returned object from a file ./jsonData.json.

Inside this file, I have this data:

Note: This is the whole JSON data loaded from the file.

import QuizData from './quizData.json'

This is a new app, so QuizData is all of the following:

[
    {
        "id": 1,
        "name": "Lesson 1",
        "topics": [
            {
                "topicID": 1,
                "topicName": "Science",
                "topicDescription": "Science quiz questions"
            },
            {
                "topicID": 2,
                "topicName": "General Knowledge",
                "topicDescription": "General Knowledge Quiz Questions"
            }
        ]
    }
]

I am trying to get the topic name for each one found and put it out as a Text.

Here is my code:

<FlatList
    data={QuizData}
    renderItem={({ item, index }) =>
        <View>
            <Text>{item.topics.topicName}</Text>
        </View>
    }
    keyExtractor={(item) => item.topicID.toString()}
/>

I have also tried:

{item.topics.[index].topicName}

and

{item.topics[index][topicName]}

But I get the error:

undefined is not an object.

I then thought perhaps its needs to be:

data={QuizData.topics}

and then change the renderItem to:

{item.topicName}

This time there is no error, but there is also no output of text to the screen.


Solution

  • You could do something like this

    import * as React from 'react';
    import { Text, View, FlatList } from 'react-native';
    
    import data from './data.json';
    
    export default function App() {
      return (
        <FlatList
          data={data}
          renderItem={({ item, index }) => (
            <View>
              {item.topics.map((v, i) => (
                <>
                  <Text>{v.topicName}</Text>
                  <Text>{v.topicDescription}</Text>
                </>
              ))}
            </View>
          )}
        />
      );
    }
    

    Where data.json is a json file in the root directory with your data.