I’m working on a project that uses Next.js and Tailwind.css. I created a utility function for structure large classNames with breakpoints in a more readable way.
The function is named responsive
and takes an object that can contain a classValue to apply for each breakpoint:
type Breakpoint = 'initial' | 'sm' | 'md' | 'lg' | 'xl' | '2xl';
function prefixClassValue(prefix: Breakpoint, classValue: ClassValue) {
return (
classValue &&
cn(classValue)
.split(' ')
.map((className) => `${prefix}:${className}`)
.join(' ')
);
}
export function responsive({
initial,
sm,
md,
lg,
xl,
'2xl': xl2,
}: Partial<Record<Breakpoint, ClassValue>>) {
return cn(
initial,
prefixClassValue('sm', sm),
prefixClassValue('md', md),
prefixClassValue('lg', lg),
prefixClassValue('xl', xl),
prefixClassValue('2xl', xl2),
);
}
The problem comes when the classes applied to breakpoints larger than initial
are not sended to the browser. The HTML elements have the correct classes, but the classes itself are not included in the layout.css file sent to the browser.
I tried to render this grid using the responsive
function:
<div
className={responsive({
initial: 'grid grid-cols-1 gap-2',
sm: 'grid-cols-3 gap-4',
md: 'grid-cols-4',
lg: 'gap-5',
xl: 'grid-cols-5',
})}
>{/*...*/}</div>
The output of this function call is grid grid-cols-1 gap-2 sm:grid-cols-3 sm:gap-4 md:grid-cols-4 lg:gap-5 xl:grid-cols-5
, and the rendered div is:
<div class="grid grid-cols-1 gap-2 sm:grid-cols-3 sm:gap-4 md:grid-cols-4 lg:gap-5 xl:grid-cols-5">...</div>
Although the classes are correctly applied, the classes itself aren’t appearing in dev tools and the breakpoints are not working.
I’ve tried different function variations and nothing worked. If I put all the classes directly to className prop, it works perfectly. I don’t know why this happens. Any thoughts on this are welcome.
Thank you for you time!
- Next.js version
14.2.3
- Tailwind.css version
3.4.3
Adrià Ribas Chico is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.