Quick Tip – Transclusion in React

March 23, 2016

no comments

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.

Add comment
facebook linkedin twitter email

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

*