Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

190
Views
Update property of hooks in another component

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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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);
      }} 
    />
  })
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!