sambhav jain
sambhav jain

Reputation: 21

copy entire object and change one property

I am trying to to setData on input change. I want to copy entire object and change only one property, when I am doing name.first it is showing error ',' expected.

    <TextField
                  fullWidth={true}
                  variant="outlined"
                  className={classes.textField}
                  name="FirstName"
                  value={data ? data.name.first : ""}
                  onChange={(e) => {setData(Object.assign({}, data, {name.first : e.target.value}))}}
                />

Upvotes: 2

Views: 1447

Answers (3)

Ammar
Ammar

Reputation: 138

You can use the spread operator

onChange={(e) => setData({ ...data, name: { ...data.name, first: e.target.value } })}

So it'll be

<TextField
    fullWidth
    variant="outlined"
    className={classes.textField}
    name="FirstName"
    value={data ? data.name.first : ""}
    onChange={(e) => setData({ ...data, name: { ...data.name, first: e.target.value } })}
/>

Upvotes: 0

Harsh Mangalam
Harsh Mangalam

Reputation: 1299

You can try some shorthand

<TextField
  fullWidth={true}
  variant="outlined"
  className={classes.textField}
  name="FirstName"
  value={data ? data.name.first : ""}
  onChange={(e) =>
    setData({ ...data, name: { ...data.name, first: e.target.value } })
  }
/>

Upvotes: 1

user12417761
user12417761

Reputation:

Try to add data like this {data} in Object.assign()

Upvotes: 0

Related Questions