how to render child components in react.js recursively

43,488

Solution 1

If I create the child nodes as an object at the top of the render method, it works fine.

export default class extends React.Component {
  let replies = null
  if(this.props.replies){
    replies = this.props.replies.map((reply) => {
      return (
        <Comment author={reply.author} body={reply.body} />
      )
    })
  }

  render() {
    return (
      <div className="comment">
        <div className="replies">{ replies }</div>
      </div>
    )
  }
}

Solution 2

Here's an alternative in ES6:

import React, { Component, PropTypes } from 'react'

export default class Comments extends Component {

  render() {

    const { children } = this.props

    return (
      <div className="comments">
        {children.map(comment =>
          <div key={comment.id} className="comment">
            <span>{comment.content}</span>
            {comment.children && <Comments children={comment.children}/>}
          </div>
        )}
      </div>
    )

  }

}

Comments.propTypes = {
  children: PropTypes.array.isRequired
}

And is some other component:

<Comments children={post.comments}/>

Solution 3

The easiest way is to create a function in the class which returns an instance of your class:

RecursiveComponent.rt.js:

var RecursiveComponent = React.createClass({
 render: function() {
  // JSX
  ....
 },
 renderRecursive: function(param1)
   return React.createElement(RecursiveComponent, {param1: param1});

});

if you use react-templates library:

RecursiveComponent.rt:

<div>
  ...
  <div rt-repeat="recursiveChild in this.props.recursiveItem.recursiveChilds">
            {this.renderRecursive(recursiveChild)}
  </div>
</div>
Share:
43,488

Related videos on Youtube

svnm
Author by

svnm

javascript, ruby, css

Updated on July 09, 2022

Comments

  • svnm
    svnm almost 2 years

    I wanted to recursively add a react component from within its own component. I saw this example of a tree component which was mapping through the child TreeNodes and adding child nodes in the same way. Unfortunately it doesn't work at all for me. The idea was to have a simple comment component, and the replies would reuse the same component.

    var Comment = React.createClass({
      render: function() {    
        return (
            <div className="comment">
    
              {/* text and author */}
              <div className="comment-text">
                <span className="author">{this.props.author}</span>         
                <span className="body" dangerouslySetInnerHTML={{__html: this.props.body}} />
              </div>
    
              {/* replies */}
              <div className="replies">
               {
                 this.props.replies.map(function(reply) {
                   <Comment body={reply.body} author={reply.author} />
                 }.bind(this))
              }
              </div>
    
          </div>
        );
      }
    });
    

    I get the following error message:

    Uncaught TypeError: Failed to construct 'Comment': Please use the 'new' operator, this DOM object constructor cannot be called as a function.

    here is an example of the JSON data passed to the component.

    { "author" : "Some user",
      "body" : "<div>Great work</div>",
      "replies" : [ { "author" : "A user replying",
            "body" : "<div Yes it was great work</div>"
          },
          { "author" : "Another user replying",
            "body" : "<div It really was great work!</div>"
          }
        ]
    }
    
    • serverpunk
      serverpunk over 9 years
      You're missing a return in the replies.map function. From the error message, it sounds like the problem is with how the top-level Comment is being created, wherever you're using it.
    • svnm
      svnm about 9 years
      thanks for that, it was probably the issue, I changed it now to the below, setting up a replies object then it is also working fine.
    • Thomas Decaux
      Thomas Decaux over 5 years
      This is not recursively at all
    • EugenSunic
      EugenSunic over 4 years
      tree component link doesn't work
  • Thomas Decaux
    Thomas Decaux over 5 years
    where is the recursion here?
  • Francisco Aquino
    Francisco Aquino over 5 years
    The <Comments /> component renders itself if it has children