Simple delete and update experiment on the list and nested list with React, currently delete doesn't work properly for both the main list and sub list, console.table()
and it seems to be caused by the Input
component, ie if I use <input value={value}>
here the value comes from the parent instead of using local state, delete works. Not sure why? Could it be Button
component is a sibling to Input
and something is not set up properly? Quick Demo: https://codesandbox.io/s/crud-playgroud-xwrip?file=/src/App3.js
import { useState } from "react";
export default function App3() {
const [list, setList] = useState([
{ val: "a", sublist: [1, 2] },
{ val: "b", sublist: [8, 4, 5] }
]);
console.table(list);
const add = (newVal)=>{
setList([...list, { val: newVal, sublist: [] },])
}
return (
<>
<Input placeholder={'add list item'} add={add}/><br/>
{list.map((e, i) => (
<ListItem key={i} index={i} item={e} list={list} setList={setList} />
))}
</>
);
}
function ListItem({ index, item, list, setList }) {
const copy = [...list];
const del = () => {
copy.splice(index, 1);
setList(copy);
};
const updateSublist = (newSublist) => {
copy[index].sublist = newSublist;
setList(copy);
// console.log(newSublist);
};
const add = (newVal)=>{
copy[index].sublist.push(newVal)
setList(copy);
}
const update = (newVal) => {
copy[index].val = newVal;
setList(copy);
};
return (
<>
<Input value={item.val} update={update} />
<Button del={del} />
<div>
{item.sublist.map((subE, subI) => (
<SublistItem
key={subI}
subIndex={subI}
subItem={subE}
subList={item.sublist}
updateSublist={updateSublist}
/>
))}
</div>
<Input placeholder={'add sublist item'} add={add} /><br/>
<div>--------------</div>
</>
);
}
function SublistItem({ subIndex, subItem, subList, updateSublist }) {
const copy = [...subList];
const del = () => {
copy.splice(subIndex, 1);
updateSublist(copy);
};
const update = (newVal) => {
copy[subIndex] = newVal;
updateSublist(copy);
};
return (
<>
<Input value={subItem} update={update} />
<Button del={del} />
</>
);
}
function Button({ del }) {
return (
<>
<button onClick={del}>X</button>
</>
);
}
function Input({ placeholder, value, update, add }) {
const [inputVal, setInputVal] = useState(value)
console.log("value: "+value, "inuptVal: "+inputVal);
// console.log(add !== undefined)
const submit = (e) =>{
if (e.keyCode === 13){
if (add !== undefined){
add(inputVal)
}
}
}
return (
<>
<input
value={inputVal}
//delete work if value={value}
placeholder={placeholder}
onChange={(e) => {
const newVal = e.target.value
if (add === undefined){
update(newVal);
}
setInputVal(newVal)
}}
onKeyDown={(e)=>{submit(e)}}
/>
</>
);
}