Cleaner Codes — React Subcomponents
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:
Then you’re giddy up to code, and this is easy. You code:
And you got this:
You feel good about yourself about the component — only to figure out there’s another design. Now a little bit more weird…
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.
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.
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:
And so we create this 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.
And thus, we create getChildrenOnDisplayName as the function that will identify them.
Finally, we restructure the Card component:
Finally, we will have a beautiful code like this:
With it being called in App.js as:
And produces the result of:
And if you want to create the same result as above, we will have:
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!