1

Just wondering if this is possible.

I have a parent component like so:

const React = require('react');    

module.exports = React.createClass({

   render: function(){

      return (

          <html lang="en">
          <head>
              <meta charset="UTF-8"></meta>
                  <title>Title</title>
          </head>
          <body>

              {this.props.child}

          </body>
          </html>

      )

   } 

});

what I would like to do is 'pass' a child component to the parent component using props.

Something like this:

const child = React.createClass({
   //// etc
});


ReactDOMServer.renderToString(<HTMLParent child={child}/>);

Normally, a parent component would have "hard-coded" reference to its children. But what I am looking for is a pattern for a parent React component to be able to "adopt" different children as needed.

Is this possible?

Perhaps the correct way to do this is something like:

    const child = React.createClass({
       //// etc
    });


    const str = ReactDOMServer.renderToString(<child />);

    ReactDOMServer.renderToString(<HTMLParent child={str}/>);
Alexander Mills
  • 90,741
  • 139
  • 482
  • 817

2 Answers2

3

This is built in React

var Parent = React.createClass({

   render: function(){

      return (
        <div>{ this.props.children }</div>
      )
   } 

})

Usage:

 ReactDOMServer.renderToString(<Parent><Children /><Parent>)
thangngoc89
  • 1,400
  • 11
  • 14
0

This is perhaps one way to do it

const React = require('react');


module.exports = function (children) {

    return React.createClass({

        renderChildren: function () {

            return children.map(function (item) {

                var Comp = item.comp;
                var props = item.props;

                return (
                    <div>
                        <Comp {...props}/>
                    </div>
                )
            });

        },

        render: function () {

            return (

                <html lang="en">
                <head>
                    <meta charset="UTF-8"></meta>
                    <title>Title</title>
                </head>
                <body>

                <div>
                    {this.renderChildren()}
                </div>

                </body>
                </html>

            )

        }

    });
};
Alexander Mills
  • 90,741
  • 139
  • 482
  • 817
  • 1
    I strongly suggest you use it like I suggested. React is all about composing components. – thangngoc89 Mar 30 '16 at 22:33
  • An example HTML component https://github.com/MoOx/statinamic/blob/eb4e94ff4d4843a258a8f2fbda7087c173b66c28/src/static/to-html/Html.js – thangngoc89 Mar 30 '16 at 22:36