Dazzy
Dazzy

Reputation: 61

Handling multiple textfield with single onChange react hooks

I have some issues with managing controls over some textfields. I have an object

let obj = {
  [
   {
    name:"a",
    adress:[{"foo":a1,"bar":a1}],
    comment:"aaaaa"
   },
   {
    name:"b",
    adress:[{"foo":b1,"bar":b1}],
    comment:"bbbbb"
   }
  ]
}

And I generate dynamic textfields

{obj.map((item, i) => {
 return <TextField name = {item.name} value={item.comment} onChange={(e)=>{handleComment(e,item.name)}}/>
})}

I want to modify comment for every specific textfield based by its name

const handleComment = (e,name) =>{
  e.preventDefault();
  setObject({...obj,comment:e.target.value})
}

I can't managed the right way to do it. I can't figure it out how to do it. If you guys can help me, it would be awesome. Thanks!

Upvotes: 0

Views: 1216

Answers (1)

Giovanni Esposito
Giovanni Esposito

Reputation: 11156

Ciao, you could use an array in handleComment function in which you can copy current state. Then update that array and set the state. Lets say you have:

const obj = [
    {
      name: "a",
      adress: [{ foo: "a1", bar: "a1" }],
      comment: ""
    },
    {
      name: "b",
      adress: [{ foo: "b1", bar: "b1" }],
      comment: ""
    }
  ];
  const [object, setObject] = useState(obj);

and return like:

return object.map((item, i) => {
    return (
      <TextField
        name={item.name}
        value={item.comment}
        onChange={(e) => {
          handleComment(e, item); 
        }}
      />
    );
  });

Then your handleComment becomes:

const handleComment = (e, item) => {
    e.preventDefault();
    let result = object;   // copy state
    result = result.map((el) => {  // map array to replace the old comment with the new one
      if (el.name === item.name) el.comment = e.target.value;
      return el;
    });
    setObject(result); // set state with new comment
  };

Here a codesandbox example.

Upvotes: 3

Related Questions