Ad

Display Element On Increase Of Counter In ReactJS

- 1 answer

I'm new to ReactJS. I need to show a text as many times as user clicks. I have tried but some how it is not working as expected. Please help.

var Paragraph = React.createClass({
renderParagraph: function(){
 for(i=0; i<this.props.data;i++){
   <p key={i}> Hello World </p>
 }
},
render: function() {
  return(
    <div>
     {this.renderParagraph}
    </div> 
  );
}
});


var Container = React.createClass({
getInitialState: function() {
  return {
    counter: 0
  }
},
increment: function() {
 this.setState({
   counter: this.state.counter + 1
 });
},
render: function() {
  return (
    <div className="well">
      <Paragraph data={this.state.counter}/>
      <button className="btn btn-primary" onClick={this.increment}> Increase Me
      </button>
    </div>
   )
  }
});

React.render(<Container />, document.getElementById('root'));

In the above code, i'm trying to render Paragraph component as many times as user clicks.

Implementation here: http://jsbin.com/jevufu/edit?js,output

Thanks in advance.

Ad

Answer

You need call method this.renderParagraph() not just pass reference this.renderParagraph., also, from method renderParagraph you need return array with Nodes,

var Paragraph = React.createClass({
  renderParagraph: function() {
    var paragraphs = [];

    for (var i = 0; i < this.props.data; i++) {
        paragraphs.push(<p key={i}> Hello World { i } </p>);
    }

    return paragraphs;
  },

  render: function() {
    return(
      <div>{ this.renderParagraph() }</div> 
    );
  }
});

Example

Ad
source: stackoverflow.com
Ad