user1354934
user1354934

Reputation: 8841

how to render an element n number of times in react

given a count, i am trying to render a button and in the text show number.

for example, if count is 5, then I am trying to make <Button>1</Button> to <Button>5</Button>.

How can I do this in react?

Upvotes: 2

Views: 199

Answers (1)

Oleksandr T.
Oleksandr T.

Reputation: 77482

You can show state inside button., and onClick event set new state

var Counter = React.createClass({
  getInitialState: function () {
    return { counter: 0 };
  },
  	
  handleClick: function () {
    this.setState({ counter: this.state.counter + 1 });
  },
  
  render: function() {
    return <div>
      <button onClick={ this.handleClick }>{ this.state.counter }</button>
    </div>
  }
});

ReactDOM.render(<Counter />, document.getElementById('container'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="container"></div>

Upvotes: 1

Related Questions