0

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 1

1

Seems like you want to do this:

this.state[`step${i}`]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.