I have a Parent component and a child Component
I am Passing an Array from Parent to child , i want the array to be filtered in Child and can be return back to parent
After filtering in child, it should return me filtered array
Parent
const Parent = () =>{
const todoData = [
{id:0,todoname:"Study",todotoday:"Completing CSS today"},
{id:1,todoname:"Coding",todotoday:"Leetcode 2 Problems"}
];
const [myArray,setmyArray] = useState(todoData);
<div className="todomain">
{
myArray.map((obj)=>{
return ( <div className="todobox" key={obj.id}>
<div className="checkcont">
<img src={check} alt="Check" className='chkbtn btn'/>
</div>
<h2 className="head" >Todo: {obj.todoname}</h2>
<h3 className="todocont">{obj.todotoday}</h3>
<div className="todoboxbtn">
<Child todoList = {todoData} />
</div>
</div> )
})
}
</div>
}
Child
const Child = ({todoData}) =>{
onst [myArray,setmyArray] = useState(todoData);
const removeElm = (id) =>{
const myNewArray = myArray.filter((currElm)=>{
return currElm.id !== id;
})
setmyArray(myNewArray);
}
return (
<div className="todoicon">
{
myArray.map((obj)=>{
return ( <div className='todobtn' key={obj.props.id}>
<img src={del} alt="Delete" className='deleteBtn btn' onClick={() => removeElm(obj.props.id)}/>
</div>)
})
}
</div>
)
}
Expected:
In Child component a delete button is there , which upon click should delete that particular Array Element and send back updated array to parent
2
Answers
If your goal is to change the state of your parent component when the user deletes an item from your TODO list, then you can simply pass the setter to your child component.
In this way you can call your component like this:
And update your child component like this:
Note that saving the Todo in a state of your child component is not necessary. When you go to update the state of the parent component, a re-render will be performed and your child will have its props updated
You can simply create a new state in the parent and pass its setter function as a prop to the child and set the value using this setter function.
Parent
Child