Maxime Heckel
Published in

Maxime Heckel

React sub-components

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

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.

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:

  • component: the component we want to find within the list of children, in our example it will be Title.

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:

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.

If you liked this article don’t forget to hit the “clap” button and if you have any other questions I’m always reachable on Twitter, or on my website. You can also subscribe to my Medium publication to not miss my next post.

Have a wonderful day
Maxime

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Maxime Heckel

Software engineer and space enthusiast. Currently working for @docker.