Hi Friends đź‘‹,

Welcome To Infinitbility! ❤️

To remove an item from the array in react native, just use the splice(index, 1) method it will delete your desired item from an array.

Like the following example, let’s take the below array of objects example here we will find an index of id 3 and delete it from the array.

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

let index = arrOfObj.findIndex(e => e.id == 3);

// 👇️ 2
console.log(index);

arrOfObj.splice(index, 1)
// 👇️
// [
//   { id: 1, name: 'Infinitbility' },
//   { id: 2, name: 'aGuideHub' }
// ]
console.log(arrOfObj);

Today, I’m going to show you How do I remove items from an array in react native, as above mentioned here, I’m going to use the splice() method to remove items from an array.

Let’s start today’s tutorial how do you remove an item from an array in react native?

In this example, we will do

  1. Create a sample array and array of objects state
  2. Remove elements from array and array of objects state
  3. Print array and an array of objects 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(["Infinitbility", "aGuideHub", "SortoutCode"]);
    const [arrOfObj, setArrOfObj] = useState([
        {id: 1, name: "Infinitbility"},
        {id: 2, name: "aGuideHub"},
        {id: 3, name: "SortoutCode"},
    ]);

    useEffect(() => {
        let array = [...arr];
        let arrayOfObject = [...arrOfObj];
        array.splice(2, 1); // here 2 is index
        arrayOfObject.splice(2, 1); // here 2 is index
        setArr(array);
        setArrOfObj(arrayOfObject);
    }, []);

    return (
        <View style={styles.container}>
            <Text>{JSON.stringify(arr)}</Text>
            <Text>{JSON.stringify(arrOfObj)}</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 splice() to remove elements from an array, and printed it on the screen.

Let’s check the output.

React Native, remove item from array example
React Native, remove item from array example

Try it yourself

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