How to dynamically add and remove elements in React?
In React, elements can be dynamically added and removed by using state.
To dynamically add elements, you can define an array in the component’s state and then update the array using the setState method. For example, if a component needs to dynamically add a list item:
import React, { useState } from 'react';
function MyComponent() {
const [list, setList] = useState([]);
const addItem = () => {
setList([...list, 'New Item']);
};
return (
<div>
<button onClick={addItem}>Add Item</button>
<ul>
{list.map((item, index) => (
<li key={index}>{item}</li>
))}
</ul>
</div>
);
}
export default MyComponent;
In the code above, the ‘list’ is a state array, the ‘addItem’ function is used to add a new item to the ‘list’ array when a button is clicked. In the rendering section, the ‘map’ method is used to iterate through the ‘list’ array to generate list items.
To dynamically remove elements, you can use the filter method to filter out the elements that need to be deleted. For example, suppose there is a component that needs to dynamically remove an item from a list:
import React, { useState } from 'react';
function MyComponent() {
const [list, setList] = useState(['Item 1', 'Item 2', 'Item 3']);
const removeItem = (index) => {
setList(list.filter((item, i) => i !== index));
};
return (
<div>
<ul>
{list.map((item, index) => (
<li key={index}>
{item}
<button onClick={() => removeItem(index)}>Remove</button>
</li>
))}
</ul>
</div>
);
}
export default MyComponent;
In the above code, the removeItem function takes an index parameter, then uses the filter method to remove the corresponding item at that index and update the list array. In the rendering section, each list item has a delete button next to it, which when clicked calls the removeItem function with the corresponding index.