Reputation: 3771
Here is a simplified version of my react code. I have a hook like this:
const [todo, setTodo] = useState();
My todo
looks like this:
todo = {
name: 'Name of my todo list',
date: 2022-09-19',
todos: [
'groceries',
'do the laundry'
]
}
In my main component I pass to "todos component" the todos:
In my todos component, I have a loop on the props to show all input with todos value
{todos.map(t => {
<input
value={t}
onChange={e => {
t = e.target.value
}}
/>
})
But unfortunately it doesn't update the todo. How do I do this? I cannot use setTodo because I'm in the child component and setTodo manage all the todo object whereas I just want to update the list of todo. My component doesn't have knowledge of the full todo object but just the list of todo.
Upvotes: 1
Views: 67
Reputation: 84912
I cannot use setTodo
You must. That is the only way to change the state.
However, you don't necessarily need to use it directly in the child component. It makes total sense to want to limit the child component so it doesn't need to know about the entire todo object. To do this, you can pass down a function that knows how to do most of the update, and then have the child component call that, passing in the few pieces of information that the child is in charge of.
For example:
const Parent = () => {
const [todo, setTodo] = useState();
return (
<Child
todos={todos}
onChange={(newValue, index) => {
setTodo(prev => {
const newArray = [...prev.todos];
newArray[index] = newValue;
return {
...prev,
todos: newArray
};
});
})
/>
);
}
const Child = ({ todos, onChange }) => {
// ...
{todos.map((t, i) => {
<input
value={t}
onChange={e => {
onChange(e.target.value, i);
}}
/>
})
}
Upvotes: 6