Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

196
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda