Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Transclusion in React

DZone's Guide to

Transclusion in React

An easy way to achieve Angular-style transclusion in React.

· Mobile Zone
Free Resource

Download this comprehensive Mobile Testing Reference Guide to help prioritize which mobile devices and OSs to test against, brought to you in partnership with Sauce Labs.

Yesterday I created a complex React menu component that needed to host another component. In order to do the same behavior in Angular v1 you would have probably used transclusion. In React in order to host a child/ren component inside a host parent component you can use the props.children property.

The following example shows a simple component that exposes the option to host other components:

export class ExampleComponent extends Component {
    render() {
        function createItem(item) {
            return (<li key={item.id} value={item.id}>{item.name}</li>);
        }

        return (<div>
                    <ul>
                        {this.props.items.map(createItem.bind(this))}
                    </ul>
                    {this.props.children}
                </div>);
    }
}

ExampleComponent.propTypes = {
    items: PropTypes.array.isRequired
}

A note – the code is written using ES2015 syntax.

In the example, the interesting part is the call to this.props.children.  Using that call you “punch a hole” inside the component. When the component is being used and the developer hosts inside of it other components they will be inserted in the same place that you put the call to this.props.children.

Here is a usage example:

<ExampleComponent items={[{ id: 1, name: 'list item 1'},{ id: 2, name: 'list item 2'}]}>
    <div>I'm transcluded</div>
</ExampleComponent>

The output of rendering the component can look like:

Code Output

All in all, this is a simple example of how to transclude a React component. 
My hope is that this post will help you to craft much more sophisticated components.

Analysts agree that a mix of emulators/simulators and real devices are necessary to optimize your mobile app testing - learn more in this white paper, brought to you in partnership with Sauce Labs.

Topics:
react ,mobile

Published at DZone with permission of Gil Fink, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}