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
Neto3y ago
Concatenation is fine
nexxel
nexxel3y ago
checkout clsx, it will help you concatenate conditionally too
royanger
royanger3y ago
+100000 for cslx. It cleans up code so much.
Brendonovich
Brendonovich3y ago
clsx + cva >>>
Unknown User
Unknown User3y ago
Message Not Public
Sign In & Join Server To View
alrightsure
alrightsureOP3y ago
Awesome definitely checking these out, thanks guys
robotkutya
robotkutya3y 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
andersgee3y 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
robotkutya3y ago
do you get proper linting with this solution?
andersgee
andersgee3y ago
yes
robotkutya
robotkutya3y 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
royanger3y 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