Hi Friends đź‘‹,

Welcome To Infinitbility! ❤️

To map or iterate an array of objects in react native, just use the map() method it will work like foreach loop and you can easily write components in it.

Like the following example, we can iterate an array of objects using the map() method.

let domains = [
    {id: 1, name: "Infinitbility", domain: "infinitbility.com"},
    {id: 2, name: "aGuideHub", domain: "aguidehub.com"},
    {id: 3, name: "Sortoutcode", domain: "sortoutcode.com"},
];

domains.map((domain, index) => console.log(domain, index));

// output
// {id: 1, name: 'Infinitbility', domain: 'infinitbility.com'} 0
// {id: 2, name: 'aGuideHub', domain: 'aguidehub.com'} 1
// {id: 3, name: 'Sortoutcode', domain: 'sortoutcode.com'} 2

Today, I’m going to show you How do i iterate an array of objects in react native components, as above mentioned here, I’m going to use the map() method iterating an array of objects.

Let’s start today’s tutorial how do you map an array of objects in react native?

In this example, we will do

  1. Create a sample array of objects state data
  2. Use the map() method and render an array of objects on a screen
  3. Call component function within map() method

Let’s write code…

import React, { useState, useEffect } from 'react';
import { Text, View, StyleSheet } from 'react-native';

const App = () =>  {
    const [domains, setDomains] = useState([]);

    useEffect(() => {
        let domainsArr = [
            {id: 1, name: "Infinitbility", domain: "infinitbility.com"},
            {id: 2, name: "aGuideHub", domain: "aguidehub.com"},
            {id: 3, name: "Sortoutcode", domain: "sortoutcode.com"},
        ];
        setDomains(domainsArr);
    }, []);

    const renderDomain = (domain) => {
        return (
            <Text style={styles.paragraph}>
                {domain.name + ' - ' + domain.domain}
            </Text>
        )
    }

    return (
        <View style={styles.container}>
            {
                domains.map((domain) => { return renderDomain(domain)})
            }
        </View>
    );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    backgroundColor: '#ecf0f1',
    padding: 8,
  },
  paragraph: {
    margin: 24,
    fontSize: 18,
    fontWeight: 'bold',
    textAlign: 'center',
  },
});

export default App;

TIP: To provide a key in your view element use something like id instead of index

As mentioned above, we are taken the example of an array of objects, use the map() to iterate, and printed it on the screen.

Let’s check the output.

React Native, map array of objects example
React Native, map array of objects example

Try it yourself

I hope it’s help you, All the best 👍.