Dr. Malte Westerloh
Dr. Malte Westerloh

Reputation: 33

TextField onChange with nested Object

I have another Question right away. I will try to explain it.

This ist the structe of my object. Inside of "allgemein" there are two variables at the moment, but it will increas by time ...

{
   id: "Abadi",
   name: "Abadi",
   type: "SC",
   allgemein: {
      charname: "Abadi",
      spieler: "Malte",
   },
   eigenschaften: {
      lebenspunkte: "30",
    },
   talente: {},
   zauber: {},
},

I get the imput like this:

const {
        type,
        name,
        allgemein: { charname, spieler },
      } = this.state,
      { charakterID } = this.props;

return (
    <form>
      <TextField
        label="type"
        value={type}
        onChange={this.handleChange("type")}
        margin="dense"
        fullWidth
      />
      <TextField
        label="name"
        value={name}
        onChange={this.handleChange("name")}
        margin="dense"
        fullWidth
      />
      <br />
      <TextField
        label="charname"
        value={charname}
        onChange={this.handleChangeAllg("charname")}
        margin="dense"
        fullWidth
        />
        <br />
      <TextField
        label="spieler"
        value={spieler}
        onChange={this.handleChangeAllg("spieler")}
        margin="dense"
        fullWidth
      />

To get the input of my TextField I am using the following handle functions:

handleChange = (n) => ({ target: { value } }) => {
  this.setState({
    [n]: value,
  });
};

handleChangeAllg = (n) => ({ target: { value } }) => {
  this.setState((prevState) => ({
    ...prevState,
    allgemein: {
      ...prevState.allgemein,
      charname: value,
    },
  }));
};

Why doesn't the last work and is there a more elegant way to handle the input?

Upvotes: 2

Views: 969

Answers (1)

Adam Jeliński
Adam Jeliński

Reputation: 1788

You made a small mistake in the handleChangeAllg. You are always changing the charname property of the object, no matter what n is provided.

handleChangeAllg = (n) => ({ target: { value } }) => {
  this.setState((prevState) => ({
    ...prevState,
    allgemein: {
      ...prevState.allgemein,
      [n]: value,
    },
  }));
};

This is a pretty good way of managing input. A small improvement could be to take the name of the property to change from the name of the input.

handleChange = ({ target: { value, name } }) => {
  this.setState({
    [name]: value,
  });
};

handleChangeAllg = ({ target: { value, name } }) => {
  this.setState((prevState) => ({
    ...prevState,
    allgemein: {
      ...prevState.allgemein,
      [name]: value,
    },
  }));
};

Then you don't have to provide the extra argument for those functions:

<TextField
  label="type"
  value={type}
  name="type"
  onChange={this.handleChange}
  margin="dense"
  fullWidth
/>

Upvotes: 2

Related Questions