Best Practices When Using Components with Tailwind

Hi all, just wondering what the best practices are for passing additional class names as props for a component using Tailwind. Is this the recommended way, or is there a better alternative?
12 Replies
Neto
Neto2y ago
Concatenation is fine
nexxel
nexxel2y ago
checkout clsx, it will help you concatenate conditionally too
royanger
royanger2y ago
+100000 for cslx. It cleans up code so much.
Brendonovich
Brendonovich2y ago
clsx + cva >>>
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
alrightsure
alrightsure2y ago
Awesome definitely checking these out, thanks guys
robotkutya
robotkutya2y ago
+1 for cva just make sure you set up your linter to work with it, but there's an example in the docs if I remember correctly
andersgee
andersgee2y ago
There are always tools like clsx and others if you want to create a design system with "variants" etc. But most of the time, and for your example I would definitely recommend writing it like this instead. with optional className prop
type Props = {
children: React.ReactNode
className?: string;
};

export function Container({ children, className = "" }: Props) {
return <div className={`flex items-center h-full ${className}`}>
{children}
</div>
}
type Props = {
children: React.ReactNode
className?: string;
};

export function Container({ children, className = "" }: Props) {
return <div className={`flex items-center h-full ${className}`}>
{children}
</div>
}
robotkutya
robotkutya2y ago
do you get proper linting with this solution?
andersgee
andersgee2y ago
yes
robotkutya
robotkutya2y ago
okay I tried it out, and you do indeed! I thought maybe the intellisense / linter doesn't pick this up, if it's a prop, but it does nice pattern, thanks! (I guess it's regexp... so yeah it makes sense that it picks it up...)
royanger
royanger2y ago
I almost always use cslx inside of className.
export function Container({ children, isActive = false, className = "" }: Props) {
return <div className={cslx(
'flex items-center h-full', ${className}
isActive ? 'border-blue-500' : 'border-grey-500'
)}>
{children}
</div>
}
export function Container({ children, isActive = false, className = "" }: Props) {
return <div className={cslx(
'flex items-center h-full', ${className}
isActive ? 'border-blue-500' : 'border-grey-500'
)}>
{children}
</div>
}
Want results from more Discord servers?
Add your server