Hi Friends 👋,

Welcome To Infinitbility! ❤️

To create an array of objects in react native, just use the [] brackets and curly brace with key value pair for the object.

Like the following example, we can create a sample array of objects like the below example using brackets and curly brace.

let arrOfObj = [
    {id: 1, name: "Infinitbility"},
    {id: 2, name: "aGuideHub"},
    {id: 3, name: "SortoutCode"},
];

console.log(arrOfObj); 
// Output
// [
//     0: {id: 1, name: 'Infinitbility'},
//     1: {id: 2, name: 'aGuideHub'},
//     2: {id: 3, name: 'SortoutCode'}
// ]

Today, I’m going to show you How do i create an array of objects in react native, as above mentioned here, I’m going to use the brackets and curly brace to create an array of objects and for adding new objects into the array going to use push() method.

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

In this example, we will do

  1. Create a sample array of objects state with sample data
  2. Use the push() method to update the array of objects state
  3. Store array of objects in a state
  4. Print array state in react native app screen

Let’s write code…

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

const App = () =>  {
    const [arr, setArr] = useState([
            {id: 1, name: "Infinitbility"},
            {id: 2, name: "aGuideHub"},
            {id: 3, name: "SortoutCode"},
        ]);

    useEffect(() => {
        let arrOfObj = [...arr];
        arrOfObj.push({id: 4, name: "somethingNew"},);
        setArr(arrOfObj);
    }, []);

    return (
        <View style={styles.container}>
            <Text>{JSON.stringify(arr)}</Text>
        </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;

Note: In the above code I have used […arr] to bypass reference then it will not cause an issue with rendering

As mentioned above, we are taken the example of an array of objects, use the push() to append a new object, and printed it on the screen.

Let’s check the output.

React Native, create array of objects example
React Native, create array of objects example

Try it yourself

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