Freestyle09
Freestyle09

Reputation: 5508

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);
    }

Upvotes: 0

Views: 51

Answers (1)

Eugene Tsakh
Eugene Tsakh

Reputation: 2879

Seems like you want to do this:

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

Upvotes: 1

Related Questions