Hi there! Not that-skilled-yet Javascript developer here, using React and Next, more specifically this template
When it comes to declare component class names, I'm using the following utility function, that combines tailwind-merge
and clsx
, as suggested here:
// utils.ts
import { clsx, type ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"
function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}
To make things easier, improve DRY and even readability, I wish to be able to dynamically insert tailwind modifiers (e.g dark:
, hover:
, md:
...) while declaring these class names, like in the following:
// page.tsx
import { cn, dark, hover, md } from '@/utils'
<Component className={cn(
"text-white text-sm",
"w-full h-10",
hover("font-bold text-lime-500"),
md(
"w-1/2 h-20",
"text-xl"
)
)}/>
To achieve so, I implemented some other utilities functions:
// utils.ts
function apply_modifier(modifier: string, ...inputs: string[]) {
return inputs.map((input) => `${modifier}:${input}`).join(" ")
}
function create_specialist_apply_modifier_function(modifier: string) {
return (...inputs: string[]) => apply_modifier(modifier, ...inputs)
}
const dark = create_specialist_apply_modifier_function("dark")
const hover = create_specialist_apply_modifier_function("hover")
const md = create_specialist_apply_modifier_function("md")
...
I tested it out and I got the string I was expecting every time, however, the results aren't being applied to the component at all, and I couldn't understand why
Even the following won't work:
<Component className={clsx(
["text-2xl", "text-white"].map((c) => `dark:${c}`).join(" ")
)}/>
I appreciate any thoughts on understand the problem and also into figure an alternative solution
Obrigado!