@MaximeHeckel

React sub-components

February 26, 2018 / 9 min read

Last Updated: February 26, 2018

This is the first article in a 3 part series about React Sub-components. Part 2 and Part 3 are available here and here.

Every React project I’ve worked on, whether it was personal or work related, got big enough at some point that their codebase became hard to understand. Every little change required more thinking but lead to a lot of inconsistencies and hacks. Among the many issues I had with such codebases, the lack of reusability of some views was the main one: it lead to a lot of copying/pasting code of complex components/views to ensure they look the same, and the resulting duplicated code didn’t make it easier to maintain nor to test.
Using a sub-component pattern can help to fix all these issues.

What exactly is a sub-component?

For this article, we’ll consider the following view as our main example: a simple Article view to render a title, subtitle, content, metadata and comments of an article object. We’ve all dealt with such views, and they can be really problematic for the reasons stated in the intro.

Example of Article view component

1
class MyArticleView extends React.Component {
2
...
3
render() {
4
return (
5
<div className={css.mainContainer}>
6
<div className={css.wrapper}>
7
<div className={css.titleContainer}>
8
<div className={css.title}>
9
<span>{this.renderTitle()}</span>
10
</div>
11
<div className={css.subtitle}>
12
<div className={css.subtitleBox}> {this.renderSubtitle()}</div>
13
</div>
14
</div>
15
<ul className={css.articlemetadata}>
16
<li className={css.item}>{this.renderAuthor()}</li>
17
<li className={css.item}>{this.renderDate()}</li>
18
</ul>
19
</div>
20
<div className={css.contentArticle}>
21
<div className={css.contentTextStyle}>{this.renderMainContent()}</div>
22
<span className={css.inlineComments}>{this.renderComments()}</span>
23
</div>
24
</div>
25
);
26
}
27
}

By using sub-components we can render the same exact view, but with a much more readable code and a reusable component. This is what the result can look like:

Article view component implemented with "sub-components"

1
class MyArticleView extends React.Component {
2
...
3
render() {
4
return (
5
<Article>
6
<Article.Title>{this.renderTitle()}</Article.Title>
7
<Article.Subtitle>{this.renderSubtitle()}</Article.Subtitle>
8
<Article.Metadata>
9
{this.renderAuthor()}
10
{this.renderDate()}
11
</Article.Metadata>
12
<Article.Content>{this.renderContent()}</Article.Content>
13
<Article.Comments>{this.renderComments}</Article.Comments>
14
</Article>
15
);
16
}
17
}

In this context, sub-components are defined as components which have their own definition declared within another parent component, and can only be used in the context of that parent component. In the example above, the Title component for instance only exists within the scope of the Article component. It can’t be rendered on its own.
I’m personally not sure about the name, but this is the best term I’ve found to refer to this pattern that I’ve learned to appreciate in my projects.
Sub-components can be seen in multiple libraries such as Recharts or Semantic-UI. The latter refers to sub-components as Modules, Collections and Views in its library, and gives you the ability to render views the same way as stated above.
This kind of pattern is really beneficial:

  • ArrowAn icon representing an arrow
    to keep views consistent: you can actually show any kind of data using the Article component above. What matters here is that regardless of its purpose, it will look the same across the whole app.
  • ArrowAn icon representing an arrow
    to keep your code tight and clean: Title, Comments, Subtitle, Metadata only make sense within Article and will only be able to be used within it (i.e. where they make sense, since these components are only used in the context of an “Article”).
  • ArrowAn icon representing an arrow
    to have easily testable views: for testing such components, Jest and snapshot testing are our allies. It gives us the ability to quickly test any combination of sub-components when using Article. We’ll see how to use Jest to test such a pattern later.

How to build sub-components

In this section we’re going to build the Article component step by step, first by trying to implement the Title sub-component.
The first thing we need in order to build sub-components within a component is a util to find children by “type” or “name” so React will know how to render our Title sub-component. We’ll pass two parameters to this util:

  • ArrowAn icon representing an arrow
    children: the list of children of Article
  • ArrowAn icon representing an arrow
    component: the component we want to find within the list of children, in our example it will be Title.

Here’s how the util findByType looks like:

fidByType function

1
import React from 'react';
2
const findByType = (children, component) => {
3
const result = [];
4
/* This is the array of result since Article can have multiple times the same sub-component */
5
const type = [component.displayName] || [component.name];
6
/* We can store the actual name of the component through the displayName or name property of our sub-component */
7
React.Children.forEach(children, (child) => {
8
const childType =
9
child && child.type && (child.type.displayName || child.type.name);
10
if (type.includes(childType)) {
11
result.push(child);
12
}
13
});
14
/* Then we go through each React children, if one of matches the name of the sub-component we’re looking for we put it in the result array */
15
return result[0];
16
};
17
export default findByType;

Now that we have our findByType util, we can start writing our Article component and the Title sub-component:

Article component with Title sub-component

1
import React, { Component } from 'react';
2
import findByType from './findByType';
3
import css from './somestyle.css';
4
// We instantiate the Title sub-component
5
const Title = () => null;
6
class Article extends Component {
7
// This is the function that will take care of rendering our Title sub-component
8
renderTitle() {
9
const { children } = this.props;
10
// First we try to find the Title sub-component among the children of Article
11
const title = findByType(children, Title);
12
// If we don’t find any we return null
13
if (!title) {
14
return null;
15
}
16
// Else we return the children of the Title sub-component as wanted
17
return <div className={css.title}>{title.props.children}</div>;
18
}
19
render() {
20
return (
21
<div className={css.mainContainer}>
22
<div className={css.wrapper}>
23
<div className={css.titleContainer}>{this.renderTitle()}</div>
24
</div>
25
</div>
26
);
27
}
28
}
29
// Lastly we expose the Title sub-component through Article
30
Article.Title = Title;
31
export default Article;

We now have the ability to use the Article component and its Title sub-component as such:

Usage of the Title sub-component

1
<Article>
2
<Article.Title>My Article Title</Article.Title>
3
</Article>

In order to extend our set of sub-components, we simply need to instantiate each one of them, write their corresponding render function, and call it in the main render function.
Below you will find the fully implemented component with all its sub-components:

Full implementation of the Article component with all its sub-components

1
// @flow
2
import React, { Component } from 'react';
3
import type { Node } from 'react';
4
import findByType from './findByType';
5
import css from './styles.css';
6
7
const Title = () => null;
8
const Subtitle = () => null;
9
const Metadata = () => null;
10
const Content = () => null;
11
const Comments = () => null;
12
13
type Props = {
14
children?: Node,
15
className?: string,
16
};
17
18
class Article extends Component<Props> {
19
static Title: Function;
20
static Subtitle: Function;
21
static Metadata: Function;
22
static Content: Function;
23
static Comments: Function;
24
25
renderTitle() {
26
const { children } = this.props;
27
const title = findByType(children, Title);
28
if (!title) {
29
return null;
30
}
31
return <div className={css.title}>{title.props.children}</div>;
32
}
33
34
renderSubtitle() {
35
const { children } = this.props;
36
const subtitle = findByType(children, Subtitle);
37
if (!subtitle) {
38
return null;
39
}
40
return (
41
<div className={css.subtitle}>
42
<div className={css.subtitleBox}>{subtitle}</div>
43
</div>
44
);
45
}
46
47
renderMetadata() {
48
const { children } = this.props;
49
const metadata = findByType(children, Metadata);
50
51
if (!metadata) {
52
return null;
53
}
54
55
return (
56
<ul className={css.articlemetadata}>
57
{metadata.props.children.map((child) => {
58
return <li className={css.item}>{child}</li>;
59
})}
60
</ul>
61
);
62
}
63
64
renderContentAndComment() {
65
const { children } = this.props;
66
const content = findByType(children, Content);
67
const comments = findByType(children, Comment);
68
69
if (!content) {
70
return null;
71
}
72
73
return (
74
<div className={css.contentArticle}>
75
<div className={css.contentTextStyle}>{content.props.children}</div>
76
<span className={css.inlineComments}>
77
{comments && comments.props.children}
78
</span>
79
</div>
80
);
81
}
82
83
render() {
84
const { children, className, ...rest } = this.props;
85
86
return (
87
<div className={css.mainContainer}>
88
<div className={css.wrapper}>
89
<div className={css.titleContainer}>
90
{this.renderTitle()}
91
{this.renderSubtitle()}
92
</div>
93
{this.renderMetadata()}
94
{this.renderContentAndComment()}
95
</div>
96
</div>
97
);
98
}
99
}
100
101
Article.Title = Title;
102
Article.Subtitle = Subtitle;
103
Article.Metadata = Metadata;
104
Article.Content = Content;
105
Article.Comments = Comments;
106
107
export default Article;

Note: the renderMetadata function is really interesting in this example, it shows how it is possible to use a single render function for two different sub-components.

Using Jest and snapshot testing to test sub-components

Snapshot testing our sub-components is probably the quickest and safest way to make sure that any combination of sub-components within the Article component will render properly. To do this we’re going to use both Jest and Enzyme. Here’s how you can write tests for our example:

Example of snapshot testing sub-components

1
import React from 'react';
2
import { mount } from 'enzyme';
3
import Article from '../';
4
5
// First we declare some mocks
6
const Content = () => <div>[Mock] Content</div>;
7
const Subtitle = () => <div>[Mock] Subtitle</div>;
8
const Comments = () => <div>[Mock] Comments</div>;
9
const Metadata = () => <div>[Mock] Metadata</div>;
10
const Title = () => <div>[Mock] Title</div>;
11
const Subtitles = () => <div>[Mock] Subtitles</div>;
12
13
it('Renders with all the sub-components', () => {
14
// Then we try to render the Article component with the desired sub-components
15
const component = mount(
16
<Article>
17
<Article.Title>
18
<Title />
19
</Article.Title>
20
<Article.Subtitle>
21
<Subtitle />
22
</Article.Subtitle>
23
<Article.Metadata>
24
<Metadata />
25
</Article.Metadata>
26
<Article.Content>
27
<Content />
28
</Article.Content>
29
<Article.Comments>
30
<Comments />
31
</Article.Comments>
32
</Article>
33
);
34
// Finally we check it matches its snapshot stored in the project
35
expect(component).toMatchSnapshot();
36
});
37
38
it('Renders with only the Content and Comments', () => {
39
// We can iterate the same process again with a different combination of sub-components
40
const component = mount(
41
<Article>
42
<Article.Content>
43
<Content />
44
</Article.Content>
45
<Article.Comments>
46
<Comments />
47
</Article.Comments>
48
</Article>
49
);
50
expect(component).toMatchSnapshot();
51
});
52
53
it('Renders with a Title and without a subtitle', () => {
54
const component = mount(
55
<Article>
56
<Article.Title>
57
<Title />
58
</Article.Title>
59
<Article.Metadata>
60
<Metadata />
61
</Article.Metadata>
62
<Article.Content>
63
<Content />
64
</Article.Content>
65
<Article.Comments>
66
<Comments />
67
</Article.Comments>
68
</Article>
69
);
70
expect(component).toMatchSnapshot();
71
});

One last note

While writing this article I noticed that sub-components wouldn’t render on IE 11 and Edge once bundled with Babel 6.26.0 and Webpack 3.10. Maybe it affects other versions, I haven’t checked yet, but all I know is that it only affected the bundled app, it worked fine when the project was running with Webpack Dev Server.

What happened? The culprit here was found when debugging the findByType util. child.type.displayName || child.type.name was returning undefined on IE and Edge for the following reason: “_type_ here is a reference to the component constructor. So if you do _child.type.name_, it references the name property on the constructor -- no supported in IE.

Reference: https://github.com/facebook/react/issues/9803

As a workaround I added a static variable called displayName for each one of my sub-components to ensure that they have a name. Here’s how it should look like on our example:

Sub-components with declared "displayName"

1
...
2
3
const Title = () => null;
4
Title.displayName = 'Title';
5
6
const Subtitle = () => null;
7
Subtitle.displayName = 'Subtitle';
8
9
const Metadata = () => null;
10
Metadata.displayName = 'Metadata';
11
12
const Content = () => null;
13
Content.displayName = 'Content';
14
15
const Comments = () => null;
16
Comments.displayName = 'Comments';
17
18
...

Liked this article? Share it with a friend on Twitter or support me to take on more ambitious projects to write about. Have a question, feedback or simply wish to contact me privately? Shoot me a DM and I'll do my best to get back to you.

Have a wonderful day.

– Maxime

Making flexible, easily testable and reusable views in React without ending in “markup hell”