skies.dev

Don't Bake Spacing into React Components with Tailwind CSS

1 min read

I don't recommend baking in margin and padding utilities inside of components.

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

This makes the component less flexible.

It may work in the first place you add the <Card />, but will it work in the second place you add it?

Instead, consider changing your component's API to accept className as a prop.

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

Now you can control the spacing around your component on a case-by-case basis.

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

And hey, if you think you know what the spacing should be most of the time, give className a default value.

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

Of course, this tip only applies to the outer-most element within the component.

There's nothing wrong with spacing utilities within a component.

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

The className prop gives you flexibility with spacing around the component.

Hopefully that helps you make your React components more flexible when using Tailwind CSS.

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