This small post is the continuation of my second article about sub-components. To fully understand this article please read that first

In Part 2 of my React sub-components series, we saw how using Context could greatly improve the original pattern I’ve described in my first post. However, one regression came along with this improvement and in this article we’ll bring a solution to it thanks to static typing.

Current issue

The sub-component pattern described in the previous post addressed a few issues of the original implementation, but introduced one regression: children that are not properly defined as sub-components are still being rendered.

Originally, the findByType util was being used to render our sub-components and would skip any unknown sub-components. The code snippet below shows this regression. You can give it a try by pulling the example project here and following the instruction in the README to run it. You can try switching the imports of <App/> in index.js to see how both implementation defer.

Incorrect usage of a subcomponent

1<Article>
2 <Article.Title />
3 {/*
4 This will render if we use the sub-component pattern described in part 2,
5 but will be skipped with the one described in part 1 (the findByType util
6 mentioned in the post will simply not render "<div></div>" as it's not
7 a known sub-components of <Article/>.
8 */}
9 <div>Hello World</div>
10 <Article.Metadata />
11 <Article.Content />
12</Article>

This regression breaks one of the main advantages of using sub-components: narrowing the scope of what can be rendered within a given component to make sure it is used properly and avoiding a messy codebase.

To fix this, as I mentioned at the end of the previous article, I decided to use static typing. The main idea here is to provide a specific type for the Article component, so that only a given list of components (i.e. our sub-components) will be rendered within it.

Flow to the rescue

Let’s see how static typing can fix the main caveat of the sub-component pattern that is implemented with contexts. I’m going to use Flow here to handle my types.

The gif below shows the actual implementation of using static typing to whitelist the sub-components of Article . You can see that before adding <div>Hello</div> as a child of Article, running Flow against my codebase returns no errors. However, once I add this extra piece of code, Flow will output the following error:

1Cannot create Article element because in property type of array element of
2property children:
3 • Either div [1] is incompatible with typeof Title [2].
4 • Or div [1] is incompatible with typeof Metadata [3].
5 • Or div [1] is incompatible with typeof Content [4].

Gif showing that running flow with a non valid sub-component fails

As you can see, Flow is aware of the type of our sub-components (and of any children of Article ), and reports that div is not compatible with one of these types.

To make sure to catch whether someone misuses Article in our codebase, we can simply add Flow as a step in our CI pipeline. Additionally, there are many editor extensions available to highlight whenever a component is not use correctly given its Flow type.

How to achieve whitelisting with Flow

First, we need to add Flow to our project. For that, I recommend following this guide. Once done, running flow at the root of the project should output no errors since we haven’t typed anything in our codebase yet.

Then we’ll need to do some modifications to our Article.js file. First, we’ll have to change any sub-components declared as a functional component to a full class. This is due to the fact that classes have their own type but functional components do not. If we want to whitelist children, this is going to be the only limitation here.

Then, we’ll have to declare the types¹ of our sub-components, i.e. the children of Article . For that we’ll declare a type ArticleSubComponent which will be of type Title or of type Metadata or of type Content .

Finally, we need to associate that type to the children prop of Article. Our component can have either 1 or more children, thus the type should either be an array of React elements of type ArticleSubComponent if Article has 2 or more children or a single React element of type ArticleSubComponent if it has 1.

The code snippet bellow shows the resulting component:

Article.js

1// @flow
2import * as React from 'react';
3
4// This creates the "Article Context" i.e. an object containing a Provider and a Consumer component
5// $FlowFixMe
6const ArticleContext = React.createContext();
7
8// We use classes here instead of functional components for our sub-components
9// so we can define a type for each one of them
10
11// This is the Title sub-component, which is a consumer of the Article Context
12class Title extends React.Component<{}> {
13 render() {
14 return (
15 <ArticleContext.Consumer>
16 {({ title, subtitle }) => (
17 <div style={{ textAlign: 'center' }}>
18 <h2>{title}</h2>
19 <div style={{ color: '#ccc' }}>
20 <h3>{subtitle}</h3>
21 </div>
22 </div>
23 )}
24 </ArticleContext.Consumer>
25 );
26 }
27}
28
29class Metadata extends React.Component<{}> {
30 render() {
31 return (
32 <ArticleContext.Consumer>
33 {({ author, date }) => (
34 <div
35 style={{
36 display: 'flex',
37 justifyContent: 'space-between',
38 }}
39 >
40 {author}
41 {date}
42 </div>
43 )}
44 </ArticleContext.Consumer>
45 );
46 }
47}
48
49class Content extends React.Component<{}> {
50 render() {
51 return (
52 <ArticleContext.Consumer>
53 {({ content }) => (
54 <div style={{ width: '500px', margin: '0 auto' }}>{content}</div>
55 )}
56 </ArticleContext.Consumer>
57 );
58 }
59}
60
61// The ArticleSubComponent type is either of type Title, Metadata or Content
62// any other type is not supported by this component, and will result in an
63// error in flow if use as a child of Article
64type ArticleSubComponents = typeof Title | typeof Metadata | typeof Content;
65
66type Property = string | Node;
67
68type ArticleObject = {
69 title: Property,
70 subtitle: Property,
71 author: Property,
72 date: Property,
73 content: Property,
74};
75
76// Here we type the props of our Article component
77type Props = {
78 value: ArticleObject,
79 // We assign the children prop its type: either an array of React elements of
80 // type ArticleSubComponents (if Article has 2 or more children)
81 // or just a React element of type ArticleSubComponents (if Article
82 // only has 1 child)
83 children:
84 | Array<React.Element<ArticleSubComponents>>
85 | React.Element<ArticleSubComponents>,
86};
87
88// This is our main Article components, which is a provider of the Article Context
89const Article = (props: Props) => {
90 return (
91 <ArticleContext.Provider {...props}>
92 {props.children}
93 </ArticleContext.Provider>
94 );
95};
96
97Article.Title = Title;
98Article.Metadata = Metadata;
99Article.Content = Content;
100
101export default Article;

There are surely other solutions to address this issue, but this is the one I’m exploring as it uses dependencies and patterns that I’m already using in most of my projects.

Feeling like playing with Flow types and sub-components? I’ve made available this specific example on a branch named flow on the same repository that I’ve used as an example for the previous post. Check it out here!

[1] The type reference doc from the Flow website was very useful when looking to type my classes https://flow.org/en/docs/react/types/#toc-react-element

If you liked this article, don't forget to share it or click here to leave a comment discuss about it on Twitter. Do you have any questions, comments or simply wish to contact me privately? I’m always reachable on Twitter or on my website!


Have a wonderful day.
Maxime


© 2019 Maxime Heckel. Made in SF.