Cleaner Codes — React Subcomponents

Mario Serano
3 min readFeb 28, 2022

Let’s say you want to create a card. That card has a header, body, and a footer. The component’s structure will be as such:

Figma for Card 1, easy, right?

Then you’re giddy up to code, and this is easy. You code:

components/Card.js
App.js

And you got this:

The result

You feel good about yourself about the component — only to figure out there’s another design. Now a little bit more weird…

The new designs…

There’s a change on the card. We need to have a styling that changes. Well, this is pretty easy since this is just the font. We just need to override the style somehow, and we can just restructure this.

components/Card.js
App.js

Voila! This should work… right? It’s kinda ugly… but it works right? Well, there’s multiple attributes, like onClick, like onHover. We need to plugin those to every single subcomponents in that component. So let’s do just that.

App.js

And you got yourself later on, with 50 lines of props that needs to be passed. Because there’s a subcomponents within the Card. So how should you restructure this? How should you deal with subcomponents in the Card?

The idea is basically to create the subcomponents as its own components, with its own separate identities.

The structure later, will be just like this:

App.js

And so we create this subcomponents:

Defining Card subcomponents

This basically states that there’s a subcomponents within the card, that each has those display names.

So, when we have children, we will be able to identify which is the Card.Header, and which is Card.Body, and Card.Footer, through its displayName.

function to identify them

And thus, we create getChildrenOnDisplayName as the function that will identify them.

Finally, we restructure the Card component:

The card component

Finally, we will have a beautiful code like this:

components/Card.js

With it being called in App.js as:

App.js

And produces the result of:

The final render

And if you want to create the same result as above, we will have:

App.js
Final render

And there’s the final render.

If we want to create onClick functions, and other kinds of properties, we just have to specify it in the subcomponents!

And that, is the introduction for React Subcomponents for your dose of cleaner code.

Thank you!

--

--