I am trying to remove an item from an array.
A simple example, parent creates and array of children.
const Parent = () => {
const [content, setContent] = useState([]);
useEffect(() => {});
const addContent = event => {
setContent(content => content.concat(
<Child key={content.length} id={content.length} removeItem={(id) => removeContent(id)}/>
));
}
function removeContent (id) {
setContent(content.slice(id, 0));
}
return(
<div onClick={(event) => addContent(event)}>
{content}
</div>
)
}
Child has a remove button.
const Child = ({id, removeItem}) => {
remove = event => {
removeItem(id);
}
return(
<button onClick={(event) => remove(event)}>
Remove
</button>
)
}
The Problem
Lets say I create 4 children in my array:
[0: {child1}, 1: {child2}, 2: {child3}, 3: {child4}]
I'll remove child3 (index 2), by clicking the remove button of child2.
It goes to my parent removeContent, but my array looks like this:
[0: {child1}, 1: {child2}]
this then deletes my entire array. Does anyone know why?