1

I'd like to insert dynamically several React component in a div HTML element. Every time that I click on button, I would like to add a new PeriodButtonContainer inside div with id="container".

This is what I've tried so far:

class Period extends React.Component {
  addPeriodHandler = () => {
    /****?????******/
  };

  render() {
    return (
      <div>
        <div id="container">
          <PeriodButtonContainer />
        </div>
        <div>
          <button id="addPeriod" onClick={this.addPeriodHandler}>
            Add a period
          </button>
        </div>
      </div>
    );
  }
}

Thanks in advance

1
  • you should increment a counter in your state, create an array of the length of the counter and map it to your element Commented Jul 11, 2018 at 21:22

1 Answer 1

6

You could keep a counter that you increment on each button click, and create that many PeriodButtonContainer components in your render method with e.g. Array.from.

Example

class Period extends React.Component {
  state = { periods: 1 };

  addPeriodHandler = () => {
    this.setState(previousState => {
      return { periods: previousState.periods + 1 };
    });
  };

  render() {
    return (
      <div>
        <div id="container">
          {Array.from({ length: this.state.periods }, (_, index) => (
            <PeriodButtonContainer key={index} />
          ))}
        </div>
        <div>
          <button id="addPeriod" onClick={this.addPeriodHandler}>
            Add a period
          </button>
        </div>
      </div>
    );
  }
}
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.