skip to Main Content

I want to reuse a component in react with tailwind but some presentation aspect of it is different in two places. I want to use similar things to dark:{class}. so I want to have something like variant_a:{class} in some places while variant_b:{class} on others. and when I call the component I want to specify which variant I’ll be using for that component such as class="variant_a".

I could create two components but I think this will be a more elegant solution. any ideas on how to achieve this?

2

Answers


  1. You could register some static variants via a Tailwind plugin, like:

    const plugin = require('tailwindcss/plugin')
    
    module.exports = {
      // …
      plugins: [
        plugin(function({ addVariant }) {
          addVariant('variant_a', '.variant_a &');
          addVariant('variant_b', '.variant_b &');
        })
      ]
    }
    

    These could then be used like:

    <div class="variant_a">
      <div class="variant_a:text-blue-500 variant_b:text-red-500">
        I will be blue.
      </div>
    </div>
    
    <div class="variant_b">
      <div class="variant_a:text-blue-500 variant_b:text-red-500">
        I will be red.
      </div>
    </div>
    
    Login or Signup to reply.
  2. If you are following PostCSS installation, you can add a @layer in your global.css file where you have imported the tailwind base classes. @layer components lets you extend the component layer to define your component classes to be used in the project.

    @tailwind base;
    @tailwind components;
    @tailwind utilities;
    
    /*Your tailwind configurations*/
    @layer components {
      .btn-blue {
        /* Here you can use @apply directive to use tailwind classes */
        @apply bg-blue-500;
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search