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
1class MyArticleView extends React.Component {2...3render() {4return (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"
1class MyArticleView extends React.Component {2...3render() {4return (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:
- 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.
- 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”).
- 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:
- children: the list of children of
Article
- 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
1import React from 'react';2const findByType = (children, component) => {3const result = [];4/* This is the array of result since Article can have multiple times the same sub-component */5const 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 */7React.Children.forEach(children, (child) => {8const childType =9child && child.type && (child.type.displayName || child.type.name);10if (type.includes(childType)) {11result.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 */15return result[0];16};17export 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
1import React, { Component } from 'react';2import findByType from './findByType';3import css from './somestyle.css';4// We instantiate the Title sub-component5const Title = () => null;6class Article extends Component {7// This is the function that will take care of rendering our Title sub-component8renderTitle() {9const { children } = this.props;10// First we try to find the Title sub-component among the children of Article11const title = findByType(children, Title);12// If we don’t find any we return null13if (!title) {14return null;15}16// Else we return the children of the Title sub-component as wanted17return <div className={css.title}>{title.props.children}</div>;18}19render() {20return (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 Article30Article.Title = Title;31export 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// @flow2import React, { Component } from 'react';3import type { Node } from 'react';4import findByType from './findByType';5import css from './styles.css';67const Title = () => null;8const Subtitle = () => null;9const Metadata = () => null;10const Content = () => null;11const Comments = () => null;1213type Props = {14children?: Node,15className?: string,16};1718class Article extends Component<Props> {19static Title: Function;20static Subtitle: Function;21static Metadata: Function;22static Content: Function;23static Comments: Function;2425renderTitle() {26const { children } = this.props;27const title = findByType(children, Title);28if (!title) {29return null;30}31return <div className={css.title}>{title.props.children}</div>;32}3334renderSubtitle() {35const { children } = this.props;36const subtitle = findByType(children, Subtitle);37if (!subtitle) {38return null;39}40return (41<div className={css.subtitle}>42<div className={css.subtitleBox}>{subtitle}</div>43</div>44);45}4647renderMetadata() {48const { children } = this.props;49const metadata = findByType(children, Metadata);5051if (!metadata) {52return null;53}5455return (56<ul className={css.articlemetadata}>57{metadata.props.children.map((child) => {58return <li className={css.item}>{child}</li>;59})}60</ul>61);62}6364renderContentAndComment() {65const { children } = this.props;66const content = findByType(children, Content);67const comments = findByType(children, Comment);6869if (!content) {70return null;71}7273return (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}8283render() {84const { children, className, ...rest } = this.props;8586return (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}100101Article.Title = Title;102Article.Subtitle = Subtitle;103Article.Metadata = Metadata;104Article.Content = Content;105Article.Comments = Comments;106107export 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
1import React from 'react';2import { mount } from 'enzyme';3import Article from '../';45// First we declare some mocks6const Content = () => <div>[Mock] Content</div>;7const Subtitle = () => <div>[Mock] Subtitle</div>;8const Comments = () => <div>[Mock] Comments</div>;9const Metadata = () => <div>[Mock] Metadata</div>;10const Title = () => <div>[Mock] Title</div>;11const Subtitles = () => <div>[Mock] Subtitles</div>;1213it('Renders with all the sub-components', () => {14// Then we try to render the Article component with the desired sub-components15const 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 project35expect(component).toMatchSnapshot();36});3738it('Renders with only the Content and Comments', () => {39// We can iterate the same process again with a different combination of sub-components40const component = mount(41<Article>42<Article.Content>43<Content />44</Article.Content>45<Article.Comments>46<Comments />47</Article.Comments>48</Article>49);50expect(component).toMatchSnapshot();51});5253it('Renders with a Title and without a subtitle', () => {54const 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);70expect(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...23const Title = () => null;4Title.displayName = 'Title';56const Subtitle = () => null;7Subtitle.displayName = 'Subtitle';89const Metadata = () => null;10Metadata.displayName = 'Metadata';1112const Content = () => null;13Content.displayName = 'Content';1415const Comments = () => null;16Comments.displayName = 'Comments';1718...
Liked this article? Share it with a friend on Bluesky or 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”