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

194
Views
React: Update a specific attribute of an array of objects

I have a rather simple requirement which is turning out to be quite complex for me. I'm developing a basic todo app with following UI:

Design

Now I need to update the array of object such that only the text of specific item should be updated. Here is my attempt but it just adds a new component on every key press:

import React, {useState} from "react";

const DynamicInput = () => {
  const [todos, setTodos] = useState([])
  
  
  const onAddClick = () => {
    setTodos(prevState => {
      return [...prevState, {id: prevState.length + 1, text: "", up: "↑", down: "↓", del: "x"}]
    })
  }
  
  const onValueUpdate = (id) => (event) => {
    let tempObject = todos[id]
    
    setTodos(prevState => {
    return [...prevState, {
        id: id,
        text: event.target.value,
        up: "Up",
        down: "Down",
        del: "x"
        }];  
    })

  }
  
  const onUpArrow = (event) => {
    console.log("On up")
  }
  
  const onDownArrow = (event) => {
    console.log("On down")
  }
  
  const onDeleteArrow = (event) => {
    console.log("On delete")
  }
  
  return (
    <>
      <button onClick={onAddClick}>+</button>
      {todos.map(todo => {
        return( 
          <div key={todo.id}>
            <input onChange={onValueUpdate(todo.id)} value={todo.text}></input>
            <button onClick={onUpArrow}>{todo.up}</button>
            <button onClick={onDownArrow}>{todo.down}</button>
            <button onClick={onDeleteArrow}>{todo.del}</button>
          </div>)
      })}
    </>
  );
};
export default DynamicInput;
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

To simply solve your problem you can change your onValueUpdate() method to this :

const onValueUpdate = (id) => (event) => {
    setTodos(prevState => {
        let data = [...prevState];
        let indexOfTodo = data.findIndex(todo => todo.id === id);
        data[indexOfTodo] = {
            ...data[indexOfTodo],
            text: event.target.value,
        };
        return data;
    });
};

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!