import * as React from "react";
const Node = ({ setSelfStateOnParent, removeSelfFromParent, id }) => {
const [state, setState] = React.useState({
name: "", // Stores name of node
children: [], // Stores the children of this node (sub-nodes)
});
function updateName(updatedName) {
setState({ ...state, name: updatedName });
}
function updateChildren(updatedChildren) {
setState({ ...state, children: updatedChildren });
}
function addChild() {
updateChildren([...state.children, { name: "", children: [] }]);
}
React.useEffect(() => {
/* If this is a sub-node, update element in parent's
* state.children array containing info about this sub-node
*/
if (setSelfStateOnParent) {
setSelfStateOnParent(state);
}
}, [state]);
return (
<div className="Node">
<header>
<div className="name">
<span>{id}</span>
{/* Text field to update state.name */}
<input
type="text"
value={state.name}
onChange={(e) => updateName(e.target.value)}
/>
</div>
<div className="btn_group">
<button
onClick={() => {
addChild();
}}
>
add child
</button>
{removeSelfFromParent && (
<button
onClick={() => {
if (removeSelfFromParent) removeSelfFromParent();
}}
>
delete
</button>
)}
</div>
</header>
{state.children && (
<ul className="children">
{state.children.map((child, childIndex) => (
<li className="child_node" key={childIndex}>
<Node
id={childIndex}
setSelfStateOnParent={(childState) => {
// Copy parent's children array to edit and update
const updatedChildren = [...state.children];
/*
* Updates the array with sub-nodes own state
*/
updatedChildren[childIndex] = { ...childState };
updateChildren(updatedChildren);
}}
removeSelfFromParent={() => {
const updatedChildren = [...state.children];
/* Removes this sub-node's info from
* parent's state.children
*/
const removedChild = updatedChildren.splice(childIndex, 1);
updateChildren(updatedChildren);
}}
/>
</li>
))}
</ul>
)}
</div>
);
};
export default Node;
When I try to debug in React DevTools, the element of state.children that I want to delete is deleted, but it still shows up in the front end.
e.g. When there are child nodes with indices 0..4, I press delete on the component with index 2; In React DevTools, the component with index 2 gets deleted, but it deletes component with index 4 in the front-end