skies.dev

Don't Bake Spacing into React Components with Tailwind CSS

2 min read

A common Tailwind mistake is baking layout spacing directly into a reusable component.

function Card({children}) {
  return <div className="my-4 p-4">{children}</div>;
}

That looks convenient at first, but it quietly makes the component harder to reuse. The first place you render it may need my-4, but the second place may need no margin at all, or a different amount of padding.

Prefer A Flexible API

A better default is to let the caller control the outer spacing.

function Card({className, children}) {
  return <div className={className}>{children}</div>;
}

Now the component is responsible for structure, while the call site decides how it should sit in the layout.

<Card className="my-4 p-4">🔥</Card>

If you want the component to have a sensible default, you can still do that.

function Card({className = 'my-4 p-4', children}) {
  return <div className={className}>{children}</div>;
}

That is a good option when the spacing is part of the component's identity. It is less useful when you expect the component to be dropped into many different layouts.

Keep Internal Spacing Internal

This advice only applies to the outer-most element of the component. There is nothing wrong with spacing utilities inside the component itself.

function Card({className, children}) {
  return (
    <div className={className}>
      <p className="p-4">{children}</p>
    </div>
  );
}

The outer element stays flexible, while the inner structure still has the spacing it needs.

A Better Rule Of Thumb

Use spacing on the component itself when:

  • the spacing is part of the component's design language
  • the component is intentionally opinionated
  • you are building a fixed pattern, not a generic primitive

Let the caller control spacing when:

  • the component will be reused in multiple layouts
  • the surrounding context determines the spacing
  • you want the component API to stay predictable

If you use Tailwind in a React codebase, this usually leads to a simpler pattern: keep structure inside the component and keep layout concerns outside it.

Hey, you! 🫵

Did you know I created a YouTube channel? I'll be putting out a lot of new content on web development and software engineering so make sure to subscribe.

(clap if you liked the article)

You might also like