Contact Info

Jaded Studio

Thoreau Blvd.
O'Fallon, MO 63366
phone: 618.219.5249
email: send me accolades

Find Me On...

Sidebar

Transclusion in React

01 Nov 2016

Playing with React and trying to build a menu 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 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
  }

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>

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.