React.js - js - add two strings and use this like variable

I want to get step property from state dynamically.

That loop generates input fields on page depending on numberOfSteps number in state

  makeInputs = () => {
    let steps = [];

    for (let i = 1; i <= this.state.numberOfSteps; i++) {
      steps.push(
        <input onChange={this.inputChangeHandler} name={"step" + i} />
      );
    }
    return steps;
  };

I set dynamically state names

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

Know I want to send this values with fetch do db, my problem is that i cannot concat variable names, I have tried:

this[this.state.step + i]

or eval function but nothing works...

My variable should be generated like this:

this.state.step1
this.state.step2
this.state.step3

form

let steps = [];

    for (let i = 1; i <= this.state.numberOfSteps; i++) {
      let stepObj = {
        id: i,
        name: eval('this.state.step' + i),
        description: "hejo"
      };
      steps.push(stepObj);
    }

1 answer

  • answered 2018-10-11 19:11 Eugene Tsakh

    Seems like you want to do this:

    this.state[`step${i}`]