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.
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;
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
can someone please explain to me how this is working?
setFoods(f.filter ( (_ , I) => i ! == index )) ;
Thank you very much bro
why we use setFoods(f => […f, newFood]) instead of setFoods([…f, newFood])
very good
1:10 isn’t it division not development
Bro, why use document.getElementById in React???
I found you accidentally ❤
bro how many languages do you know
Great 🎉
Please make Reactjs projects as well
for deleting the elements can we use updater functions as well? like setFoods((f) => f.filter((_, i) => i !== index));
Now i am pro in react pls do redux i will share this vid as possible
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.
Hey Bro code do you do a cybersecurity tutorial too ?
Good Explanation bro
thanks for your vids man, they are truly helpful 🙏 love from Argentina❤
can you please create a video about how can your website send an email to someone?
Code bro i love u