iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🍣

Getting Started with Tailwind Variants

に公開
2023/06/05

https://www.tailwind-variants.org/

What is Tailwind Variants?

Tailwind Variants a first-class variant API library for TailwindCSS.
Source: https://www.tailwind-variants.org/docs/introduction

As stated in the documentation, Tailwind Variants is a technology that combines TailwindCSS features with a first-class Variant API. Since it is built with TypeScript, it is type-safe and serves as a utility library that does not depend on any specific framework.

The term "Variant API" mentioned here is influenced by the CSS-in-JS library called Stitches, and Tailwind Variants imports that concept into TailwindCSS.

The word "Variants" literally means "mutations" or "variations," and by using the Variant API, it becomes easy to add multiple versions (variations) to a single component.

Example of Stitches' Variant API

In Stitches, you can add variants using styled() as follows.

const Button = styled('button', {
  // base styles

  variants: {
    variant: {
      primary: {
        // primary styles
      },
      secondary: {
        // secondary styles
      },
    },
  },
});

// Use it
<Button>Button</Button>
<Button variant="primary">Primary button</Button>

Alternatively, you can also write it using css() like this.

const button = css({
  // base styles

  variants: {
    variant: {
      primary: {
        // primary styles
      },
      secondary: {
        // secondary styles
      },
    },
  },
});

// Use it
<div className={button()}>Button</div>
<div className={button({ variant: 'primary' })}>Primary button</div>

Let's Try Out Tailwind Variants

TailwindCSS Setup

Since it is a library built on top of TailwindCSS, you need to set up TailwindCSS in advance.

Installation

Once TailwindCSS is set up, let's install Tailwind Variants.

$ npm install tailwind-variants

Base Styles

In Tailwind Variants, you generate class names using tv() as follows.

import { tv } from 'tailwind-variants';

const button = tv({
  base: 'bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded',
});

// button()
// => "bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded"
export const Button = () => {
  return <button className={button()}>Button</button>;
};

As shown above, the base key in the object passed as the first argument becomes the base style.

Although it looks like the base string is returned as-is as the return value of button(), it is processed internally by tailwind-merge, so you can avoid inefficient duplication of class names in TailwindCSS.

For example, this results in the following behavior.

const style = tv({
  base: 'bg-blue-500 bg-red-500',
});

style()
// => "bg-red-500"

By the way, you can also turn off tailwind-merge behavior by setting twMerge to false.

const style = tv({
  base: 'bg-blue-500 bg-red-500',
}, {
  twMerge: false
});

style()
// => "bg-blue-500 bg-red-500"

Variants

Variants are considered a crucial feature, as suggested by the library's name, Tailwind Variants. Using variants, you can easily add multiple versions of styles to the same component.

To add variants, you use the variants key. In the following example, primary and secondary colors are set for color. You specify which variant to use with an argument, like button({ color: 'primary' }).

const button = tv({
  base: 'text-white p-4',
  variants: {
    color: {
      primary: 'bg-blue-500',
      secondary: 'bg-red-500',
    },
  },
});

button({ color: 'primary' })
// => "text-white p-4 bg-blue-500"

button({ color: 'secondary' })
// => "text-white p-4 bg-red-500"

While only colors are set above, you can also define multiple variants. In the following example, both color and size are configured.

const button = tv({
  base: 'text-white p-4',
  variants: {
    color: {
      primary: 'bg-blue-500',
      secondary: 'bg-red-500',
    },
    size: {
      small: 'text-sm p-2',
      base: 'text-base p-4',
      large: 'text-lg p-6',
    },
  },
});

button({ color: 'primary', size: 'small' })
// => "text-white bg-blue-500 text-sm p-2"

button({ color: 'secondary', size: 'large' })
// => "text-white bg-blue-500 text-base p-6"

If you look at size here, you can see that the p-4 from base is being overwritten. In this way, classes defined in variants overwrite the base styles.

Boolean Variants

You can also set variants using boolean values, such as for a disabled flag.

const button = tv({
  base: 'text-white p-4',
  variants: {
    color: {
      primary: 'bg-blue-500',
      secondary: 'bg-red-500',
    },
    // Set boolean variants
    disable: {
      true: 'pointer-events-none opacity-20',
    },
  },
});

button({ color: 'primary', disable: true });
// => "text-white p-4 bg-blue-500 pointer-events-none opacity-20"

Setting Default Values

To set default values for variants, use the defaultVariants key.

const button = tv({
  base: 'text-white',
  variants: {
    color: {
      primary: 'bg-blue-500',
      secondary: 'bg-red-500',
    },
    size: {
      small: 'text-sm p-2',
      base: 'text-base p-4',
      large: 'text-lg p-6',
    },
  },
  defaultVariants: {
    color: 'primary',
    size: 'base',
  },
});

button()
// => "text-white bg-blue-500 text-base p-4"
// The values in defaultVariants become the defaults
// button() becomes equivalent to button({ color: 'primary', size: 'base' })

Responsive variants

Some people may find writing media queries for responsive design in TailwindCSS a bit tedious. In Tailwind Variants, in addition to the traditional method, you can handle TailwindCSS breakpoints as follows:

const button = tv(
  {
    base: 'text-white',
    variants: {
      color: {
        primary: 'bg-blue-500',
        secondary: 'bg-red-500',
      },
      size: {
        small: 'text-sm p-2',
        base: 'text-base p-4',
        large: 'text-lg p-6',
      },
    },
  },
  {
    responsiveVariants: ['md', 'lg'],
  }
);

button({
  color: 'primary',
  size: {
    initial: 'small',
    md: 'base',
    lg: 'large',
  },
})
// => "text-white bg-blue-500 text-sm p-2 md:text-base md:p-4 lg:text-lg lg:p-6"
Preparations for handling responsive variants

To use responsive variants in Tailwind Variants, you need to modify your tailwind.config.js as a preliminary step.

tailwind.config.js
const { withTV } = require('tailwind-variants/transformer')

/** @type {import('tailwindcss').Config} */
module.exports = withTV({
  content:  ["./index.html", "./src/**/*.{js,ts,jsx,tsx}"],
  theme: {
    extend: {},
  },
  plugins: [],
})

For more details, please see the following documentation:
https://www.tailwind-variants.org/docs/getting-started#responsive-variants-optional

Although not covered in this article, there are other features such as compoundVariants, which allows you to add variants that depend on other variants.

Slots

Slots allows you to create styles for multiple components divided into parts at once. It might be hard to visualize with words alone, so let's look at an actual code example.

import { tv } from 'tailwind-variants';

const card = tv({
  slots: {
    figure: 'w-48 p-4 border-2 border-solid bg-gray-100 text-center',
    avatar: 'inline-block w-full',
    caption: 'mt-2 text-gray-900 font-bold',
  },
});

const { figure, avatar, caption } = card();

export const Card = () => {
  return (
    <figure className={figure()}>
      <img
        className={avatar()}
        src="avatar.png"
        alt="Avator"
      />
      <figcaption className={caption()}>Caption</figcaption>
    </figure>
  );
};

/*
Result:
<figure class="'w-48 p-4 border-2 border-solid bg-gray-100 text-center">
  <img src="avatar.png" alt="Avator" class="inline-block w-full">
  <figcaption class="mt-2 text-gray-900 font-bold">Caption</figcaption>
</figure>
*/

You can also use slots and variants in combination as follows:

const card = tv({
  slots: {
    figure: 'w-48 p-4 border-2 border-solid bg-gray-100 text-center',
    avatar: 'inline-block w-full',
    caption: 'mt-2 text-gray-900 font-bold',
  },
  variants: {
    color: {
      light: {
        figure: 'bg-white',
        caption: 'text-black',
      },
      dark: {
        figure: 'bg-black',
        caption: 'text-white',
      },
    },
  },
});

// Specify variants
const { figure, avatar, caption } = card({ color: 'dark' });

figure()
// => "w-48 p-4 border-2 border-solid text-center bg-black"

avatar()
// => "inline-block w-full"

caption()
// => "mt-2 font-bold text-white"

While I won't go into more detail about Slots in this article, you can also perform Slot composition and use them in conjunction with responsive variants.

Overwriting Styles

You can easily overwrite styles using the class / className keys.

import { tv } from 'tailwind-variants';

const button = tv({
  base: 'text-white p-4 bg-blue-500',
});

button({ class: 'bg-red-500' })
// => "text-white p-4 bg-red-500"

// Alternatively, the same can be done with className
button({ className: 'bg-red-500' })
// => "text-white p-4 bg-red-500"

Even when using slots, you can similarly overwrite styles using the class / className keys.

const card = tv({
  slots: {
    figure: 'w-48 p-4 border-2 border-solid bg-gray-100 text-center',
    avatar: 'inline-block w-full',
    caption: 'mt-2 text-gray-900 font-bold',
  },
});

const { figure } = card();

figure({ class: 'text-start' });
// => "w-48 p-4 border-2 border-solid bg-gray-100 text-start"
// text-center is overwritten by text-start

Extending Styles

You can also extend styles using the extend key.

const baseButton = tv({
  base: 'p-4 bg-gray-100',
});

// Extend with extend
const successButton = tv({
  extend: baseButton,
  base: 'bg-green-700 text-white',
});

successButton()
// => "p-4 bg-green-700 text-white"

Alternatively, you can also concatenate the return values of the functions as follows.

const baseButton = tv({
  base: 'p-4 bg-gray-100',
});

const successButton = tv({
  base: [baseButton(), 'bg-green-700 text-white'],
});
successButton()
// => "p-4 bg-green-700 text-white"

Extending styles is not limited to base; you can also extend other keys such as variants or slots. Below is an example of extending variants in addition to base.

const baseButton = tv({
  base: 'p-4 bg-gray-100',
  variants: {
    size: {
      small: 'p-2 text-sm',
      large: 'p-6 text-lg',
    },
  },
});

const successButton = tv({
  extend: baseButton,
  base: 'bg-green-700 text-white',
  variants: {
    disable: {
      true: 'opacity-20 pointer-events-none',
    },
  },
});

successButton({ size: 'small', disable: true });
// => "bg-green-700 text-white opacity-20 pointer-events-none p-2 text-sm"

Conclusion

I wrote this article because I believe there will be more opportunities to consider Tailwind Variants as the development of the library progresses. The content introduced in this article is only a part of the features of Tailwind Variants, so if you are interested, please give it a try!

References

https://www.tailwind-variants.org

Discussion