-1

Tailwind docs say that we should not pass dynamic pieces of class name as props because it will not work, and well it does not.

There are other options. One of them is to predefine object with actual tailwind classes and then passing a prop to pick a set of classes eg:

const colorVariants = {
    blue: 'bg-blue-600 hover:bg-blue-500',
    red: 'bg-red-600 hover:bg-red-500',
  }

But that is not as flexible as I would like it to be so I came up with falling back to inline styles like so:

const props = defineProps({
    headerPadding: {
        type: String,
        required: false,
        default: '10px'
    },
    contentPadding: {
        type: String,
        required: false,
        default: '10px'
    },
});

const styles = computed(() => {
    return {header: `padding: ${props.headerPadding}`};
});

And then I do

<div :style="styles.header" class="flex">Header</div>

Now this works perfectly fine. I am just wondering if there is anything super bad about this approach or if there is a good reason to avoid it?

Robert
  • 1,206
  • 1
  • 17
  • 33

1 Answers1

0

I find pre-defining an object to be better personally. That way all my styles are tailwind classes. Although separate object, its only relevant for cases where i need this dynamic definitions, and feel it is easier to maintain rather than having strings of inline-styles.

I don't see anything wrong with your approach. But you can also try the below approach in some cases..you can define the class with array syntax..

<div :class="[ largepadding ? 'p-8' : 'p-4', danger ? 'bg-color-red' : 'bg-color-success']"></div>

and define only the dynamic attributes as props instead of the entire styles.

thezohaan
  • 324
  • 1
  • 10