1

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.

1
  • The value and the name are the same thing?? You're using ingName for both. That seems...odd. And if you're changing it, it shouldn't be the key. Commented May 31, 2021 at 9:53

1 Answer 1

2

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.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.