How to keep Tailwind DRY
Tags: tailwindcss, css, javascript, react
Published: 2021-08-06 09:24:28

<!-- wp:paragraph -->
<p>There's many complaints I see online about Tailwind: it's WET, not DRY, it's the same as inline styles, you can't make global changes, and it's hard to read. I understand how this may seem to be the case when you first start working with Tailwind. The thing to bear in mind is <strong>Tailwind is nothing like traditional CSS, and you shouldn't treat it as such</strong>.
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>There's lots of ways that Tailwind can benefit us, such as its tiny bundle size and super-fast prototyping capabilities. I explained a bit more about that in a <a href="https://npmrundev.wordpress.com/2021/08/04/6-reasons-to-use-tailwind-over-traditional-css/" target="_blank">previous article</a>. But we can only get these benefits if we use it in the right situation; used in the wrong context, Tailwind will only bring you headaches.</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2>When is the wrong time to use Tailwind CSS?</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>The first thing I would recommend <strong>against</strong> using Tailwind for is plain HTML static websites. When you're building a static site, you will inevitably end up copy and pasting HTML, since there's likely to be more than one occurrence of the same component/section on a single page. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>This is totally fine if you're using a traditional CSS methodology such as <a href="http://getbem.com/">BEM</a>: your CSS and HTML exist completely separately, so you can rely on your CSS as your single source of truth for how your website will look. If you change a CSS class, the change will be reflected everywhere the class is used without having to update the HTML. In this way, it doesn't really matter <em>too much</em> if you've copy and pasted some HTML.</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>// you can copy and paste these classes anywhere
&lt;button class="button button--negative"&gt;&lt;/button&gt;

&lt;button class="button button--negative"&gt;&lt;/button&gt;

// but you could also break rules like this
&lt;div class="button"&gt;&lt;/div&gt;</code></pre>
<!-- /wp:code -->

<!-- wp:image {"id":217,"sizeSlug":"large","linkDestination":"none"} -->
<figure class="wp-block-image size-large"><img src="https://npmrundev.files.wordpress.com/2021/08/html-files-suck.png?w=263" alt="" class="wp-image-217"/><figcaption>Separation of concerns is traditionally defined by language</figcaption></figure>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>This is about as much as you can do when it comes to <strong>separation of concerns</strong> with CSS and plain HTML. Personally, I still think this method isn't properly DRY since you're copy and pasting the same code in multiple places, but it's about the best you can do with basic HTML- something that never sat right with me while I was learning CSS. To make this system truly DRY, you would want to use some form of templating or a component-based framework so you could only write HTML for a section one time, and then re-use the component wherever you like. This brings me onto...</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2>When is the right time to use Tailwind CSS? </h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>I'm glad you asked! If you don't want to repeat yourself when building websites with Tailwind, you're probably going to want to use some kind of JavaScript framework. Whether it's React, Vue or some other new-fangled framework, the important thing is that you can build JS components which can be reused over and over. You might be able to get it to work with PHP templates, but I'd say this method is best for JavaScript since you can keep your HTML, JS and CSS all in the same file.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>That's the real way Tailwind should be used: as an entirely different paradigm where separation of concerns doesn't mean separating HTML, CSS and JS, it means separating entire components instead, and keeping everything related to that component inside one file or folder. It's a pretty different way of working to how we're used to with its own challenges, but this method has some great benefits:</p>
<!-- /wp:paragraph -->

<!-- wp:list -->
<ul><li>Components can behave independently of each other and be used across different projects without much hassle</li><li>Components can be tested on their own so you don't need to worry about things changing later on</li><li>Prototyping is much faster since you don't need to write a custom class for every single element</li><li>Full access to use JavaScript for more advanced conditional styling than with regular HTML</li><li>Encourages component composition - once you have a bunch of components, it's easy to build pages or even new variants of components by combining what you already have</li></ul>
<!-- /wp:list -->

<!-- wp:heading -->
<h2>Embracing component-based architecture</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Once you have your HTML, JavaScript and CSS all in one place, you'll realise it's much easier to contain components within their own folders rather than having resources stretched across your whole project in different file trees. Working in this way opens up new opportunities, such as being able to use JavaScript to dictate your styles and building more complex logic for views.</p>
<!-- /wp:paragraph -->

<!-- wp:image {"id":219,"sizeSlug":"large","linkDestination":"none"} -->
<figure class="wp-block-image size-large"><img src="https://npmrundev.files.wordpress.com/2021/08/filez-1.png?w=275" alt="" class="wp-image-219"/><figcaption>File structure in component-based development</figcaption></figure>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>Here's some tips to help you adjust to component-based development:</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2>1. Break components down into small, reusable pieces</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Have you ever noticed, when looking at a design, that there tend to be lots of repeating patterns? You can take advantage of this with class composition. It's common to see a 50/50 layout with text on one side, and some type of media on the other. I tend to call them <code>SplitContent</code> blocks. There are often variants on this, perhaps some of the text is a different size or the media slot is filled with a carousel instead of an image.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Instead of building two components that use the exact same styles for the most part, you could create a container component with props, slots where you can add any kind of content. You could set up logic for your styles inside - maybe you want a prop that changes which side the content will appear on, or add padding to a certain side. Alternatively, you could just add a prop which can be passed a string of class names, giving you the ability to customise the container as it's used in different contexts.</p>
<!-- /wp:paragraph -->

<!-- wp:image {"id":212,"sizeSlug":"large","linkDestination":"none"} -->
<figure class="wp-block-image size-large"><img src="https://npmrundev.files.wordpress.com/2021/08/breaking-down-components-01.png?w=1024" alt="" class="wp-image-212"/></figure>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>For areas where I want to use SplitContent as a dynamic content block with a CMS such as Wordpress, I might create a <code>Handler</code> component which breaks down the style options defined in the CMS and passes on the relevant combinations of components.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>You might, for example, want your client to only have access to one SplitContent component in the CMS, but have the choice to create many different layouts using that one component. Some of the choices might include:</p>
<!-- /wp:paragraph -->

<!-- wp:list -->
<ul><li>Which type of content do you want on each side?</li><li>Which side should each content type be on?</li><li>Does this component need a different colour scheme?</li></ul>
<!-- /wp:list -->

<!-- wp:paragraph -->
<p>These options can be taken in by the component Handler and it will return the correct layout, while keeping all this logic contained within itself so the other components can still be used across different components.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>I usually keep everything related to SplitContent under one folder, and add a subfolder of smaller pieces which make up the main components:</p>
<!-- /wp:paragraph -->

<!-- wp:image {"id":215,"sizeSlug":"large","linkDestination":"none"} -->
<figure class="wp-block-image size-large"><img src="https://npmrundev.files.wordpress.com/2021/08/filez-2-1.png?w=264" alt="" class="wp-image-215"/></figure>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>This is just one example; essentially, your components should all have a single purpose so it's easier to build larger and more complex components using the pieces you have created.</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2>2. Use JS to build class lists</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>If you find Tailwind hard to read, you're not alone. It's one of the most common complaints and I can understand why: you have to read each class to understand what's going on, which doesn't work for everyone.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>It may help to rely on JavaScript to build your class names. I often prefer this method over composing new CSS classes for the sake of it, especially when they might only be used in one place. Some people might say this is the same as using the @apply directive, but if the class isn't going to be used anywhere else there's no reason to write a whole new class for it. Writing classes with JavaScript like this helps to keep everything related to that component in a similar place, rather than placing it miles away in the CSS folder.</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>// components/Modal/View.jsx

export default function ModalView () {
  const modalContainerClass = "bg-white p-4 rounded shadow";
  const modalHeadingClass = "heading-1 text-darkgrey";

  return (
    &lt;aside className={modalContainerClass}&gt;
      &lt;h1 className={modalHeadingClass}&gt;...&lt;/h1&gt;
    &lt;/aside&gt;
  );
}</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>Storing classes in JavaScript variables makes it a little clearer what is trying to be accomplished with it, while also opening up the opportunity to use more advanced logic than would be possible with CSS.</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2>3. Use props to extend components</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>One of the problems we encounter with Tailwind compared to normal CSS is that we lose the ability to extend a basic version of a component into a new modified version with classes:</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>// _button.scss

.button {
  padding: 20px;
  border: 1px solid black;
}
.button--negative {
  border-colour: red;
}

// index.html

&lt;button class="button"&gt;Accept&lt;/button&gt;
&lt;button class="button button--negative"&gt;Cancel&lt;/button&gt;</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>Of course we could manually add the <code>border-red</code> Tailwind class to any button we want to make negative, but what if there's more than one style? What if the background and text colour also change?</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>// this would be a nightmare if the negative styles ever changed

&lt;button class="p-5 border-red bg-red text-white"&gt;Cancel&lt;/button&gt;</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p><strong>The solution: Extend your components using JavaScript</strong></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>When we make the switch over to component-based development, we gain the ability to use JavaScript in place of CSS for creating components. Since you're no longer tied to a separate stylesheet, you can create variants of your components by abstracting them to different files, using your base component as the starting point.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>One of the most flexible ways of doing this is to pass class names down as props, and merge them with the existing classes on a component. This is an example of <a href="https://reactpatterns.com/#merge-destructured-props-with-other-values">merging destructured props with other values</a>, as shown on the fantastic resource <a href="https://reactpatterns.com/">reactpatterns.com</a>.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Here's how our button variants might look using this method:</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>// components/Button/index.jsx

export default function Button = ({ classnames, handleOnClick, label }) {
  const buttonClass = &#91;
    "p-5 border-1", // default button styles
    classnames      // any additional styles
  ].join(' ');
  
  return (
    &lt;button className={buttonClass} onClick={handleOnClick}&gt;
      {label}
    &lt;/button&gt;
  )
}

// components/Button/Negative.jsx

export default function ButtonNegative = (props) {
  return (
    &lt;Button
      classnames="border-red bg-red text-white"
      {...props}
    /&gt;
  )
}</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>Now we can use <code>index.jsx</code> as the base layer of our button, and keep all the logic on that level, while also having variants of that button clearly defined without any change to functionality. This way, if the styles change later on, anywhere <code>&lt;ButtonNegative /></code> is used will reflect changes made in that file.</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2>4. Move view logic and business logic to separate files</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>This is quite a general tip for working with JavaScript frameworks, but in Tailwind it can help even more so because it separates your styles from your business logic without relegating them to a completely different folder. You can enter your Button folder, and know that everything in that folder will be related to buttons.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Once you've got everything in one place, you can start to break it down further: In React, you can keep the way your component looks separate from how it behaves. Here's an example of this:</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>// components/Carousel/View.jsx (view logic only)
export default function CarouselView ({ slides }) {
  return (
    &lt;SomeCarouselPlugin&gt;
      {Array.isArray(slides) &amp;&amp; slides.map(slide =&gt; (
        &lt;CarouselSlide {...slide} /&gt;
      ))}
    &lt;/SomeCarouselPlugin&gt;
  )
}

// components/Carousel/Jobs.jsx (business logic only)
export default function JobsCarousel () {
  const &#91;jobs, setJobs] = useState(null);
  
  const fetchJobs = async () =&gt; {
    const res = await request({
      url: 'my-api-url.com/jobs?limit=16',
      method: 'GET'
    })
    setJobs(res.data)
  }
  
  useEffect(() =&gt; {
    fetchJobs();
  }, &#91;])
  
  return !!jobs ? (
    &lt;CarouselView slides={jobs.map(job =&gt; ({
      title: job.title,
      description: job.description,
      salary: 'Up to ' + job.salary.max
    }))} /&gt;
  ) : &lt;&gt;Loading...&lt;/&gt;
}</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>If we wanted to make another carousel which used the same styles, perhaps we want the carousel to be filled with staff members instead of jobs, we could do that by creating a new container component in <code>Carousel/Staff.jsx</code>.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>This massively helps with breaking down huge components with hundreds or even thousands of lines, and this method means you could also include extra layers if you wanted to for even more customisation. This system of extension makes it easier to break down what a component is supposed to be doing, while making sure you don't repeat yourself.</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2>5. Use class composition for containers, text styles and anything used between components</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>That's right: Even when components are your source of truth, there is still a place for custom classes. For example, you are likely to use a container class on many different components with a max width, margin: auto and some side padding. Since these aren't likely to change, it makes sense to compose a new custom class using the @apply directive. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Personally, I also like to include typographic classes such as for headings, standard blocks of content and the like. These are things that don't necessarily make a lot of sense to create a new JavaScript component for, but they combine the same styles in multiple places nevertheless.</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>.page-wrap {
  @apply max-w-page mx-auto px-4 tablet:px-5 laptop:px-6;
}

.paragraph {
  @apply text-16 font-body leading-loose;
}

// we can still create variants of .paragraph
&lt;p class="paragraph text-white"&gt;Hello world!&lt;/p&gt;</code></pre>
<!-- /wp:code -->

<!-- wp:heading -->
<h2>6. When composing classes, avoid using margins</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>You can make classes more reusable by making them position agnostic. If you leave out properties such as margins which only affect the position of the element, you are able to reuse it more often.</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>// _typography.scss

.heading-2 {
  @apply text-black text-24 bold;
}</code></pre>
<!-- /wp:code -->

<!-- wp:code -->
<pre class="wp-block-code"><code>&lt;h2 className="heading-2 mb-4"&gt;Hello world!&lt;/h2&gt;</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>This might not be what you want in every situation - maybe you <em>do</em> want every heading to have a certain margin. But for many cases it's a trick worth keeping in mind that makes your components much more flexible and less dependent on their position on the page.</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2>7. Treat tailwind.config.js as your source of truth</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>In SCSS or LESS, you might create variables for constants such as colours, fonts and max widths. You can reuse those variables anywhere in your CSS, and if you change the variable this change will be reflected everywhere it's used.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Tailwind works in much the same way, except <em>everything</em> is defined by variables. That means not just the text or background colours you can use, but also spacing, sizing, borders and almost any other property you can think of. You can make use of this with the <code>theme</code> object in <code>tailwind.config.js</code>, or extend the default theme with the <code>extend</code> object.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>This file defined the way your whole app will look: If your designer has used a design system which commonly uses numbers like <code>4, 8, 12, 16, 32</code> etc. you can build that system right into your CSS:</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>spacing: {
  1: '4px',
  2: '8px',
  3: '12px',
  4: '16px',
}</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>These classes are then ready to use, straight away, and in the case of the <code>spacing</code> property will be applied to <code>padding</code>, <code>margin</code> and <code>relative</code> positioning classes such as <code>left</code> and <code>right</code>.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Don't forget that you can also use regular JavaScript to generate some of these properties, which can save a bit of time and clean the file up. I like to make a <code>const</code> containing an array similar to the one above, and using it for <code>spacing</code>, <code>width</code>, <code>height</code> and any other similar properties - even <code>font size</code>.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>I've also entertained the idea of such a spacing/font system generated using the <a href="https://grtcalculator.com/">golden ratio</a>, which might be a great option for fast prototyping while also maintaining a great visual flow.</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2>8. Use tools to spot repeating patterns</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>On the topic of composing classes, there are some great tools to help you find repeating patterns in your class lists so you can refactor these into their own generic classes.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>One of the most useful is Refactor CSS, a VS Code extension that automatically finds and presents very similar strings of classes, which helps when finding common patterns to abstract into new classes. Class strings will be highlighted if they have more than 3 classes and these 3 classes repeat more than 3 times in the current document. The order of classes is ignored, so you don't need to worry about maintaining a <a href="https://www.matuzo.at/blog/ordering-css-properties/">property sort order</a> to make sure the tool works.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>If you <em>are</em> worried about property sort order (Tailwind is much more readable if you are) then you can use another tool to deal with that for you: <a href="https://github.com/heybourn/headwind">Headwind</a>. This VS Code extension will format your Tailwind classes on save and group them by their function, making sure everything is where you expect it.</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>// before saving
&lt;div class="bg-red container mb-6 text-white"&gt;&lt;/div&gt;

// after saving
&lt;div class="container mb-6 text-white bg-red"&gt;&lt;/div&gt;</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>You can also change the regex of Headwind, so you can customise the sort order exactly how you like. </p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2>Conclusion</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>I'll won't pretend moving to this way of working is particularly easy, and there are many problems that still need solving. We're still in the early (ish) days of utility-first frameworks and component-based development, so everything hasn't been figured out yet.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Despite this, I feel confident that we'll start to see new tools, packages and methodologies that aim to tackle any issues we may face. What we can get out of this approach are lightweight, fast applications that are truly DRY. Isolated, independent components are great for building across different platforms, so I think we'll see a lot of companies building headless systems picking up this way of working.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>I write more articles like this one about headless systems and component-based development over on my blog at <a href="https://npmrundev.wordpress.com/">npm run dev</a>. Check it out if you want, and I'd love to get some feedback on my thoughts and writing style. Thanks for reading!</p>
<!-- /wp:paragraph -->