1

I've been playing with ReactJS and have two components like:

/** @jsx React.DOM */

var MyDiv = React.createClass({
   render: function () {
      return (
         <div>
             Hello World
         </div>
      )
   }
});

var MyClickableDiv = React.createClass({
   addDiv: function () {
      alert("Hello World"); //For testing
   }
   render: function () {
      return (
         <div>
             <MyDiv />
             <a href='#' onClick={this.addDiv}>Add new MyDiv</a>
         </div>
      )
   }
});

What I'm trying to do is: upon clicking "Add new MyDiv", I want to add a new MyDiv component under the first MyDiv that I already have.

1 Answer 1

2

I think a more react-minded approach would be to make the state of whether the second div is present or not explicit and put all the rendering inside the render function instead of splitting it, half in render and the other half in addDiv.

var MyClickableDiv = React.createClass({

   getInitialState: function(){
       return {showDiv: false};
   },

   addDiv: function () {
       this.setState({showDiv: true});
   },

   render: function () {
      return (
         <div>
             <MyDiv />
             {this.state.showDiv ? <MyDiv /> : null}
             <a href='#' onClick={this.addDiv}>Add new MyDiv</a>
         </div>
      )
   }
});

If you want addDiv to keep adding divs when you click it again, change the state so that instead of a boolean flag you keep a list of the extra divs that should be rendered.

Sign up to request clarification or add additional context in comments.

2 Comments

Would the list of extra divs then need to iterate over these to display them? I was going to set the state to: showDiv: [], and then use a for loop? Or is there an easier way?
Yes that is the idea. You can find a concrete example in the React tutorial when they create a CommentList component.

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.