React Native Push Element in Array Example

Jun 01, 2021 . Admin

Hi Dev,

This Blog shows you how to push element in array in react native. i explained simply about how to push object in array in react native. In this article, we will implement a how to add json object to array in react native. i would like to show you react native add object to array. So, let's follow few step to create example of react native add value to array.

Here, i will give you three simple example to adding key value in array with node. so, let's see bellow example how to push object in array in react native app.

Example: 1
import React, { Component } from "react";
import {View} from 'react-native';

const MyWebtutsComponent = () => {

    const myArray = [1, 2, 3, 4, 5, 6];

    myArray.push(7);

    console.log(myArray);

    return (
        <View>
        </View>
    );
};

export default MyWebtutsComponent;
Output
Array [
  1,
  2,
  3,
  4,
  5,
  6,
  7,
]
Example: 2
import React, { Component } from "react";
import {View} from 'react-native';

const MyWebtutsComponent = () => {

    const myObjArray = [
        {id: 1, name: "Dharmik" },
        {id: 2, name: "Bhavesh" },
        {id: 3, name: "Piyush" }
    ];

    myObjArray.push({id: 4, name: "Mehul"});

    console.log(myObjArray);

    return (
        <View>
        <View>
    );
};

export default MyWebtutsComponent;
Output
Array [
  Object {
    "id": 1,
    "name": "Dharmik",
  },
  Object {
    "id": 2,
    "name": "Bhavesh",
  },
  Object {
    "id": 3,
    "name": "Piyush",
  },
  Object {
    "id": 4,
    "name": "Mehul",
  },
]
Example: 3
import React, { Component } from "react";
import {View} from 'react-native';

const MyWebtutsComponent = () => {

    const myObjArray = [
        {id: 1, name: "Dharmik" },
        {id: 2, name: "Bhavesh" },
        {id: 3, name: "Piyush" }
    ];

    myObjArray.unshift({id: 4, name: "Mehul"});

    console.log(myObjArray);

    return (
        <View>
        <View>
    );
};

export default MyWebtutsComponent;
Output
Array [
  Object {
    "id": 4,
    "name": "Mehul",
  },
  Object {
    "id": 1,
    "name": "Dharmik",
  },
  Object {
    "id": 2,
    "name": "Bhavesh",
  },
  Object {
    "id": 3,
    "name": "Piyush",
  },
]

It will help you...

#React Native