Next.js Discord

Discord Forum

Tailwind Conditional classes

Answered
Anay-208 posted this in #help-forum
Open in Discord
So, I saw this url: https://tailwindcss.com/docs/content-configuration#class-detection-in-depth

const sizes = {
  md: 'px-4 py-2 rounded-md text-base',
  lg: 'px-5 py-3 rounded-lg text-lg',
}

const colors = {
  indigo: 'bg-indigo-500 hover:bg-indigo-600 text-white',
  cyan: 'bg-cyan-600 hover:bg-cyan-700 text-white',
}

export default function Button({ color, size, children }) {
  let colorClasses = colors[color]
  let sizeClasses = sizes[size]

  return (
    <button type="button" className={`font-bold ${sizeClasses} ${colorClasses}`}>
      {children}
    </button>
  )
}
Answered by averydelusionalperson
yes, that was just an example that how classes will get recognized in javascript too, not only in classNames
View full answer

19 Replies

In the above code provided in the web I'll use the Button component, however, how do I exactly have to provide the size there, because I need it to be responsive
because it's an object, you can reference the key to it. Objects can reference with a key and the key can be a string. So just use a string ^^
I mean if I do this:
<Button color="indigo" size="sm">
...
</Button>

I'll only be able to refer to 1 size acc to this code
What are you expecting?
@averydelusionalperson What are you expecting?
I'm expecting for only classes for sm to apply, if defined
@averydelusionalperson `sizes['sm']` should work right?
sizes['sm'] if defined, it'll only add those classes to elements, making it unresponsiv
I'm confused, so if sm is defined, you're getting the class. what else do you need :thinq:
o.0
so you want to use tailwind screen breakpoints
and apply those classes
?
@Anay-208 exactly, so I don't think it'll be the best approach
yes, that was just an example that how classes will get recognized in javascript too, not only in classNames
Answer
because @B33fb0n3 told me I could do something like this: https://discord.com/channels/752553802359505017/752647196419031042/1218083828174684183
he did, but he never said you could that method for responsiveness, but yeah cn is good for conditional classNames
@Anay-208 I think you should close this thread