Alisa T Morgan
Alisa T Morgan

Reputation: 687

dynamic setState to add new dynamic property in react

I have this scenario where I have to add multiple and dynamic property to an array of object. Says it's lang = ['en', 'fr', 'more'], how can I produce a object structure like this

Below is my failed attempt:

class App extends React.Component {
  state = {
    lang: ["en", "fr"],
    items: [
      {
        id: 1,
        value: {
          en: "abc",
          fr: "hello"
        }
      }
    ]
  };
  onChange = (e, i) => {
    this.setState({
      items: this.state.items.map(o => ({
        ...o,
        value: {
          [this.state.lang[i]]: e.target.value //need fix
        }
      }))
    });
  };
  render() {
    return (
      <div className="App">
        {this.state.lang.map((o, index) => (
          <div>
            <input
              onChange={e => this.onChange(e, index)}
              placeholder={o}
              type="text"
            />
            <br />
          </div>
        ))}
        <br />
        <pre>{JSON.stringify(this.state, null, 2)}</pre>
      </div>
    );
  }
}

https://codesandbox.io/s/p746jn313q

Upvotes: 2

Views: 96

Answers (1)

Bernardo Siqueira
Bernardo Siqueira

Reputation: 414

If I understood what you're trying to do correctly, you just needed to spread the value object inside of your map:

onChange = (e, i) => {
    this.setState({
      items: this.state.items.map(o => ({
        ...o,
        value: {
          ...o.value,  // <- this
          [this.state.lang[i]]: e.target.value
        }
      }))
    });
  };

I've also edited the codesandbox: https://codesandbox.io/s/13vo5rrjwj

Upvotes: 1

Related Questions