How to update arrays in state using React JS 🍎

Posted by


In React JS, updating arrays in state involves manipulating the state in a way that is immutable, meaning that the original state object is not modified but rather a new state object is created with the updated array.

Let’s go through a step-by-step tutorial on how to update arrays in state in React JS:

Step 1: Set up a React component
First, create a new React component using the class syntax or functional component if you are using hooks. For this tutorial, I will be using the class component syntax.

import React, { Component } from 'react';

class ArrayUpdateComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      items: ['apple', 'banana', 'cherry'],
    };
  }

  render() {
    return (
      <div>
        {this.state.items.map(item => <div key={item}>{item}</div>)}
      </div>
    );
  }
}

export default ArrayUpdateComponent;

Step 2: Update the array in state
To update the array in state, you can use the setState method provided by React. Usually, you will want to update the array based on some user input or event. Let’s say we want to add a new item to the array when a button is clicked:

class ArrayUpdateComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      items: ['apple', 'banana', 'cherry'],
    };
  }

  addItem = () => {
    this.setState(prevState => ({
      items: [...prevState.items, 'date'],
    }));
  };

  render() {
    return (
      <div>
        {this.state.items.map(item => <div key={item}>{item}</div>)}
        <button onClick={this.addItem}>Add Item</button>
      </div>
    );
  }
}

In the addItem method, we use the spread operator ... to create a new array with all the elements from prevState.items and add a new item, in this case, ‘date’.

Step 3: Update specific item in the array
If you want to update a specific item in the array, you can use the map method to iterate over the array and update the desired item based on its index. Let’s say we want to update the second item in the array:

class ArrayUpdateComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      items: ['apple', 'banana', 'cherry'],
    };
  }

  updateItem = () => {
    this.setState(prevState => ({
      items: prevState.items.map((item, index) => {
        if (index === 1) {
          return 'grape';
        }
        return item;
      }),
    }));
  };

  render() {
    return (
      <div>
        {this.state.items.map(item => <div key={item}>{item}</div>)}
        <button onClick={this.updateItem}>Update Item</button>
      </div>
    );
  }
}

In the updateItem method, we use the map method to iterate over the array and check if the current index is equal to 1 (i.e., the second item in the array), then return ‘grape’ as the updated item. Otherwise, we return the original item.

Conclusion:
In this tutorial, we learned how to update arrays in state in React JS in an immutable way using the setState method. By following these steps, you can easily manage and update arrays in state within your React components.

0 0 votes
Article Rating

Leave a Reply

26 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@BroCodez
1 hour ago

import React, { useState } from 'react';

function MyComponent() {

const [foods, setFoods] = useState(["Apple", "Orange", "Banana"]);

function handleAddFood(){

const newFood = document.getElementById("foodInput").value;

document.getElementById("foodInput").value = "";

setFoods(f => […f, newFood]);

}

function handleRemoveFood(index){

setFoods(foods.filter((_, i) => i !== index));

}

return (<div>

<h2>List of Food</h2>

<ul>

{foods.map((food, index) =>

<li key={index} onClick={() => handleRemoveFood(index)}>

{food}

</li>)}

</ul>

<input type="text" id="foodInput" placeholder="Enter food name"/>

<button onClick={handleAddFood}>Add Food</button>

</div>);

}

export default MyComponent;

@alanit8459
1 hour ago

Hello bro code, you are truly a professor. I miss you very much. Thank you. I have a question. If you want to add the item to Array

exam:function addItemCorrect(item) {

setItems(prevItems => […prevItems, item]); // This correctly creates a new array.

}

its not work to add array
i see this way in site mastering react to do that just your way to add array or what
please answer me

@jackal_sniperr
1 hour ago

can someone please explain to me how this is working?

setFoods(f.filter ( (_ , I) => i ! == index )) ;

@otabekmadaminov-z2i
1 hour ago

Thank you very much bro

@fastscript1343
1 hour ago

why we use setFoods(f => […f, newFood]) instead of setFoods([…f, newFood])

@tataloo7314
1 hour ago

very good

@frozenwater1017
1 hour ago

1:10 isn’t it division not development

@RychAhlberg
1 hour ago

Bro, why use document.getElementById in React???

@urvish_xyz
1 hour ago

I found you accidentally ❤

@_amonimus_
1 hour ago

bro how many languages do you know

@OCEMTechZone
1 hour ago

Great 🎉

@rishabhkedia9304
1 hour ago

Please make Reactjs projects as well

@RED-so9mp
1 hour ago

for deleting the elements can we use updater functions as well? like setFoods((f) => f.filter((_, i) => i !== index));

@raki0125
1 hour ago

Now i am pro in react pls do redux i will share this vid as possible

@ahmedelsehelly
1 hour ago

Guys! You all Thank Bro like me for his effort to provide this awesome materials, so hasn’t the time come for us to thank our lord Allah who gives us an awesome brain to understand this masterpiece 🙂 I really hope you all to wardship allah by the way he wants.

@maskedman0677
1 hour ago

Hey Bro code do you do a cybersecurity tutorial too ?

@eharsha7389
1 hour ago

Good Explanation bro

@Gian_sas
1 hour ago

thanks for your vids man, they are truly helpful 🙏 love from Argentina❤

@kuru6029
1 hour ago

can you please create a video about how can your website send an email to someone?

@l213dhanesh3
1 hour ago

Code bro i love u

26
0
Would love your thoughts, please comment.x
()
x