Injecting React components into other React components

So the challenge was, our List component should use a ListItem component to render each item. However, on another page, the same list should be rendered but using a different list item component. You might be thinking, why not just create 2 list components with 2 different list item components? The aim was to reduce duplication and the need to restyle pretty much identical components.

A bit more background info.

One of the lists needed to show transactions for a user. Each of those transactions would need to be expandable and show details when the user expanded it. So this list item component includes a summary of stuff to show in the clickable bit, and details in the lower portion that gets revealed when the list item is expanded.

However, on another page, another almost identical list would need to show the same items but only the summary part, and each list item would not be expandable.

The solution

Our approach was to specify a default ‘ListItem’ prop that the list would use. This meant that we’d be able to pass one to the list optionally. Here’s a bit of code explaining it (some implementation details removed)…

import ListDetails from '/ListDetails'
const List = ({ items, ListItem = ListDetails }) => (
  , index) =>

List.propTypes = {
    items: PropTypes.array,
    ListItem: PropTypes.func

List.defaultProps = {
    ListItem: ListDetails

Now the only issue here was that the defaultProps didn’t seem to do anything. I needed to set a js default parameter in the function definition. Whether that’s a react issue I’m not sure but I left it in for clarity.

But what this now means is that a different ListItem component can be injected creating another list. Like this…


So now when the list renders, it’ll use the ListDetailsSummary component instead. This example is a bit simple but it does highlight the way to set default components and then inject them.

Leave a Reply