score:2

Accepted answer

you can put the inner components in an array, iterate over them and then render them. something like this:

var react = require('react/addons');

// components
var textblock = require('../text_block.jsx');
var paperheader = require('../header_paper.jsx')
var sectionheader = require('../header_section.jsx');
var tableofcontents = require('../table_of_contents.jsx');

var page = react.createclass({

  render: function() {
    var contents = [
      <paperheader title={"page title"} authors={["cole gleason"]} />,
      <sectionheader title={'first section'} size={'large'} />,
      <textblock key={"text_first"}>
        <p>
          text goes here.
        </p>
      </textblock>,
      <this.props.activeroutehandler/>
    ];

    var titles = contents.map(function(item) {
      if (item.title && some_other_requirement) {
        return item.title;
      }
      return undefined;
    });

    return (
      <div>
        <toc titles={titles} />
        {contents}  
      </div>
    );
  }
});

module.exports = page;

but i can't help but feel like you're not really using react for the right reason and in the right way. you're treating react components like simple templates. something like this makes more sense:

var react = require('react/addons');

// components
var page = require('../page.jsx');
var section = require('../section.jsx');
var textblock = require('../textblock.jsx');

var app = react.createclass({
  render: function() {
    return (
      <page title='page title'>
        <section title='section title'>
          <textblock>
            <p>text goes here</p>
          </textblock>
          <textblock>
            <p>text goes here</p>
          </textblock>
        </section>
        <this.props.activeroutehandler />
      </page>
    );
  }
});

module.exports = app;

it's important to give things the right structure. i think this makes more sense because there's now a real relation between parents and children. textblocks that belong to a section should be situated inside the section. now this doesn't solve your table of contents problem but it's a start. it helps, for example, that now all direct children of page are sections, so you could do more with that.

if you want to build a real dynamic table of contents at runtime you should look into another place to store your content. you're mixing templates with content right now, and that's not ideal. communication in react components really only goes in one way (down the tree), so trying to pass data from a component back to a sibling or parent is not easy nor a good idea. look into flux for more about how your data should flow.

another good read: https://medium.com/@dan_abramov/smart-and-dumb-components-7ca2f9a7c7d0


Related Query

More Query from same tag