How to Create Fully Reusable React Components
Table of Contents
Introduction
Creating a React component is fairly easy, just a function like this.
Then you can call them using JSX like <Card />
, and it’s done.
However, to do them correctly is the reason that I write this blog. I’ve been wanting to write this for quite some time.
Doing them correctly may come naturally to developers who have been writing React for quite a while, but not for beginners. This is something that I learned the hard way over experience, nobody really taught me this. I want you who are currently reading to get them quickly.
The Common Flaw
If you look at the Card component that I created above, it has one crucial flaw: it’s not fully reusable.
But wait, it is reusable?! I can use them multiple times in different files.
Well yes, you can.
But they are not fully reusable.
A fully reusable component is what I call a component that is enjoyable to use. While the flawed ones frustrate you every time you need to customize them. It’s something that actually helps you code quickly by being fully reusable.
First, let's see how the flawed component looks like.
Flawed Component in Action
Let’s say we have a layout like this
We can easily achieve them using this code:
I use Tailwind CSS for this demo, but the concept applies to all solutions.
So we have a three-column grid, and we map all of the cards inside that grid. Inside the card we have a product props that renders the title. Pretty simple right?
Here’s how it went haywire.
Customization in Flawed Components
One day your lovely designer has requests:
- Make the first card span over 2 columns (it’s for featured products)
- When we click a product with a title containing ‘yay’, I want them to shoot out confetti by calling
confetti()
.
Well, you could create two brand new components called FeatureCard
and ConfettiCard
, but it’s counter-productive. Everything inside is totally the same, except one uses two columns, and one shoots confetti.
Usually, when have this kind of situation, we rely upon custom props for each condition. But it goes downhill pretty quickly as the requirements grow.
I agree that using custom props sometimes is the best solution, but we can totally solve this problem if we can directly pass className
and onClick
directly into the component.
Fully Reusable Component as A Solution
So what we basically need is to have all props that are in a div, that concludes className
, onClick
, onHover
, title
, aria-label
, style
, about
, id
, onMouseEnter
, onMouseLeave
—yeah, you got my point.
It’s A LOT.
Don’t worry. We have a type for that, may I introduce React.ComponentPropsWithoutRef<'div'>
. So instead of adding each and every component props, we can use this helpful type.
React.ComponentPropsWithoutRef
also applies to any element you’re using: <'input'>
, <'button'>
, anything!
For those of you who are not familiar with ...
, it actually represents 2 distinct operators: Rest Parameters & Spread Operators
- Rest Parameters (line 6) is used to get all of the properties from objects when destructuring
- Spread Operators (line 8) is used to spread all of the properties back to the object.
The best thing is we now get autocomplete! Woohoo!
With the updated component, we can finally make our designer happy with this implementation
We can add the two-columns feature by adding a custom className
, and the confetti feature by adding an onClick
directly in the Card
component.
Important Note about Fully Reusable Component
While it is a good practice to spread all of the props, do note that not all component needs to be fully reusable.
For example, a ProductList
component that renders a list of products, probably only needs to be customizable in the className
props. You can use Pick
for that, and take only the className
props.
We can just pick what we need from React.ComponentPropsWithoutRef<'div'>
and use them in our component.
Some components that might need to be fully reusable are:
- Reusable basic components like
Button
,Input
,Select
,Textarea
, etc. - Reusable UI components like
Modal
,Popover
,Tooltip
, etc.
Do emphasize on the word reusable here. Make sure you're using this 'fully reusable component' concept to a reusable component.
Common Pitfalls & Solutions
By using fully reusable components, there are some pitfalls that you might encounter. I compiled some of them along with the solutions that I came up with.
Class Name Conflict
If you’re using Tailwind CSS, sometimes merging classes will cause a conflict.
We merge the className
using clsx
function, so any class that we pass outside of the component will be reflected in the final code.
However, in the rendered code we will have two different margin-top classes.
Which is not good. We can use tailwind-merge library to solve that.
tailwind-merge's function will return the latest value in the parameter. So it will prioritize our mt-12
over the mt-4
. Basically what we need.
I usually create a wrapper with clsx
like this
So we now can merge conflicts and compose classes neatly.
You can safely customize your component now!
Multiple Class Names
When you start to have more items inside the component, it can be quite confusing as to how to pass a className
to a specific element.
Let’s say our Card
component has a title, description, and image. We already use className
props for the wrapper div. How can we customize the title class?
In my experience, I always use the normal className
for the outermost element (wrapper). The solution is to create another object for a specific element that I might need.
Here I created a classNames
object with title
, description
, and image
property. Then we can use them to merge the class in the respective element.
If you're using Tailwind CSS IntelliSense, another pro tip is to add this to your VSCode settings.
Adding this will enable Tailwind CSS IntelliSense to autocomplete in the classNames
object.
Components With Ref
You might notice that the type name is ComponentProps_Without_Ref
, yes there is another type called ComponentProps_With_Ref
.
This is a needed case if you’re also forwarding ref to your component. I won’t explain in detail about ref forwarding, maybe in the next post (comment if you’d like me to write about it).
Simply, ref forwarding is needed when you want to access the ref value of your component. Usually external library like Radix does.
You can add the type like this.
Only then you can access the ref.
See how I easily add type and disabled props because we’re using a fully reusable component? *chef’s kiss*
Conclusion
Please use fully reusable components. Your teammates and your future-self will thank you.