React sub-components Part 3: Whitelisting sub-components with flow

Adding more control to the sub-component pattern with Flow types

A more accessible, readable, mobile-friendly and up to date version of this story is available on my personal blog!

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.

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: