Insert component into another component

What is the preferred way to insert a component into another component? I have an object oriented application structure where the View only knows about its parent view. Since all of my components are "dynamic" components, I don't know the structure of the component beforehand.

I tried it in two different ways with the following generic code:

/** @jsx React.DOM */
var component = React.createClass({
    render: function () {
        return (
            <div>
                .. many elements here ..
                {this.props.children}
            </div>
        );
    }
});
var subcomponent = React.createClass({
    render: function () {
        return (
            <div>test</div>
        );
    }
});

var parentView = React.renderComponent(
    <component>.. subelements</component>,
    document.getElementById('reactContainer')
);

      

1. Several displayed components

var subView = React.renderComponent(
    <subcomponent />,
    parentView.getDOMNode()
);

      

The problem is that the internal components of the super components are being replaced by the injected component. Other errors also appear. It looks like this is not the React way of doing this.

2. Introducing a subcomponent using setProp with one renderComponent

Another approach is to set up child support.

parentView.setProps({
    children: <subcomponent />
});

      

This works almost as expected, but also has some disadvantages. This is a dump of children only to the injected component. I could get around this:

parentView.setProps({
    children: [parentView.props.children, <subcomponent />]
});

      

But now childView is managing the children of its parent. But I could extract this for the parentView method.

Another disadvantage is that when the depth of the view is deeper than 2, there is no reference to the React component because only the rootView is visible through React.renderComponent

and so I can only do setProps on the root view.

I think I need one React.renderComponent

for each view, but I don't know how to insert it into the parent.

+3


source to share


1 answer


In most cases, the preferred way to pass a component to another component is to use special child support (like you show in your example):

var component = React.createClass({
    render: function () {
        return (
            <div>
                .. many elements here ..
                {this.props.children}
            </div>
        );
    }
});

      



you can read here

+1


source







All Articles