Deniz Firat
Deniz Firat

Reputation: 159

ReactJS modify array of objects spesific property

i got array of objects that assigned in state and i want to modify a property with input field. I tried some below :

 <input
         key={item.ingName}
           type="text"
           className="form-control"
           placeholder={item.ingName}
           name="ingName"
           value={item.ingName}
           onChange={(e) => {
             item.ingName = e.target.value
            setIngredients([...ingredients])}}
         />

and array is like :

    ingredients : [{ingName: "meat", quantity: "1", unit: "kilogram"},
{ingName: "pickles", quantity: "100", unit: "grams"}]

These one only adds first letter that i wrote in keyboard.I need to achieve that proper working input field.

Upvotes: 1

Views: 72

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074355

You're directly modifying the object, which isn't allowed with React's state mechanism. Instead, you need to copy the object, not just the array it's in:

onChange={(e) => {
    setIngredients(ingredients.map(ingredient => {
        if (ingredient === item) {
            // This is the one we want to update, make and update a copy
            return {...ingredient, ingName: e.currentTarget.value};
        }
        // Not the one we want to update, we can keep using it
        return ingredient;
    }));
}}

A couple of side notes:

  • Notice I used currentTarget, not target. It's not important in this specific example because the element is an input, which by definition can't have children, so target and currentTarget will be the same thing. But it can be important in many other situations, such as with button or select elements.
  • Since you're changing ingName based on user input, ingName shouldn't be the key of the element. The user could make the ingName the same as another ingName. Instead, give the object some unique identifier and use that.

Upvotes: 2

Related Questions