I have a parent component that I want to use to dynamically add and remove an stateful component, but something weird is happening.
This is my parent component and how I control my list of FilterBlock
import React from 'react'
import FilterBlock from './components/FilterBlock'
export default function List() {
const [filterBlockList, setFilterList] = useState([FilterBlock])
const addFilterBlock = () => {
setFilterList([...filterBlockList, FilterBlock])
}
const onDeleteFilterBlock = (index) => {
const filteredList = filterBlockList.filter((block, i) => i !== index);
setFilterList(filteredList)
}
return (
<div>
{
filterBlockList.map((FilterBlock, index) => (
<FilterBlock
key={index}
onDeleteFilter={() => onDeleteFilterBlock(index)}
/>
))
}
<button onClick={addFilterBlock}></button>
</div>
)
}
You can assume FilterBlock is a stateful react hooks component.
My issue is whenever I trigger the onDeleteFilter from inside any of the added components, only the last pushed FilterBlock gets removed from the list even though I remove it based on its index on the list.
Please check my example here: