Hommer Smith
Hommer Smith

Reputation: 27852

React Component with subcomponents or render HTML in parent?

I have a question regarding React patterns. When rendering a component, is it appropriate for this component to render several sub-components, or is it ok to render some HTML in the parent component. Example:

If I have a box that has a heading and a body with list of elements, should I do:

var Box = React.createClass({
  render: function() {
    <div className="box">
      <HeadingBox />
      <BodyBox />
    </div>
  }
});

Or is it ok to do this:

var Box = React.createClass({
  render: function() {
    <div className="box">
      <div className="heading">
        <div> Heading1 </div>
        <div> Heading2 </div>
      </div>
      <BodyBox />
    </div>
  }
});

Any rules to follow here?

Upvotes: 0

Views: 611

Answers (1)

opportunato
opportunato

Reputation: 447

It all depends on a context.

The general practice is that if you want to reuse the markup anywhere — you should go with the separate component, so you don't have to repeat yourself. Also if you find yourself writing a large portion of HTML (over 50 lines, for example), separating it into subcomponents will also help.

In other cases, just going with plain HTML will do.

You can find a good description on how best to organize your React code here. (section Separating UI details from interaction logic)

React is no different then other programming framework — it goes best with DRY (Don't repeat yourself).

Upvotes: 2

Related Questions