44 ms·
Using spacing components makes sense for small applications where there is a predictable set of spacings used everywhere in the app. Once you get to the size o
by hjanssen 7y ago
Using spacing components makes sense for small applications where there is a predictable set of spacings used everywhere in the app.
Once you get to the size of an app which requires a dashboard, and many specific distances, some just a tiny bit smaller or bigger, this gets unwieldy very fast. You end up coding around the spacer component or not using it entirely for some situations which makes the whole approach kinda useless.
The approach I take is the "pass your own classname"-approach. Im sure somebody has found a fancy name for it.
Having a componenent A:
const A = ({ className }) => (
<div className={`${COMPONENT_CLASSNAME} ${className}`}>
Hello, World!
</div>
)
You can then just pass your own classname from the parent into the child component. If your component A does not define any margins, it should be easy to define those and not break anything. As simple as that. I find that to be way more flexible than a spacer component, because most of the time, spacing depends heavily on context. The spacing component therefore either becomes too complex and unwieldy or does not get used at all.
The approach from above does have a drawback: if you dont pass a className to your component, the resulting class attribute will contain "COMPONENT_CLASSNAME undefined". I have not found that to ever be a problem, although if you really want to, you can also write the template string as follows to mitigate this:
`${COMPONENT_CLASSNAME} ${!!className ? className : ""}`
But I do find that to be unnecessarily verbose.
- ickelbawd 7y agoYour template string logic doesn't actually mitigate the problem. Short-circuit evaluation in JavaScript means that `falsey && something_else` will always evaluate to `falsey` and then you'll still get undefined in your className string. You would have to use a ternary to avoid this.
- hjanssen 7y agoYes you are right, I have edited my post. It is pretty late.