here i want to delete the node but as soon as i click the delete button it delete the whole root component
here it it the header1 component
function Header1(){
const [input,setInput]=useState({
title:"",
content:""
})
const [items,setItems]=useState([])
function handleCheck(event){
const {name,value}=event.target;
setInput(prevValue=>{
return {
...prevValue,
[name]: value}
})
}
function addItem(){
setItems( prevValue=>{
return [...prevValue,input]
}
)
setInput("")
}
function deleteItem(id){
setItems(prevValue=>{
prevValue.filter((item,index)=>{
return index!==id
})
})
}
return(<>
<div className="h-1">
<div className="i-1">
<input onChange={handleCheck} name="title" placeholder="title" value={input.title}/>
<input onChange={handleCheck} name="content" placeholder="description" value={input.content}/>
<button onClick={addItem}>add</button>
</div>
</div>
{ items.map((item,value)=>{
return <Note key={value} id={value} title={item.title} des={item.content} del={deleteItem} />
})}
</>
)
}
export default Header1;
here is the notes component ,here the adding is work but when the deleting part came ,it delete the main root component when i click delte element i would like to delete the component
function Note(props){
function handleCheck(){
props.del(props.id);
}
return(
<>
<div className="note-container">
<div className="container">
<p className="note-title">{props.title}</p>
<p className="note-content">{props.des}</p>
<button onClick={handleCheck}
>delete</button>
</div>
</div>
</>
)
}
export default Note;
This function...
function deleteItem(id){
setItems(prevValue=>{
prevValue.filter((item,index)=>{
return index!==id
})
})
}
... doesn't do what you expect it does. Note that the callback function supplied as setItems param doesn't actually return anything: as {} are wrapping the function's body, it "expects" proper return statement. Without it, undefined is the result.
Here's one way to fix this:
function deleteItem(id){
setItems(prevValue=>{
return prevValue.filter((item,index)=>{
return index!==id
})
})
}
... to be consistent. Alternatively, you can just drop the {} and use expressions directly:
function deleteItem(id){
setItems(
prevValue => prevValue.filter(
(item,index) => index!==id
)
);
}
Without braces, result of expression put after => is treated as this function's return value.