render TailwindCSS array of colors in Nextjs
Answered
Siberian Accentor posted this in #help-forum
Siberian AccentorOP
function generateColors(count: number): string[] {
const colors: string[] = [];
for (let i = 0; i < count; i++) {
const color = Math.floor(Math.random() * 16777215).toString(16);
colors.push(`bg-[#${color}]`);
}
return colors;
}
const arrayOfColors = [
{
id:"1",
data:{
colors: generateColors(1),
}
},
{
id:"2",
data:{
colors: generateColors(1),
}
}
]
// rest of the code
{data.colors?.length === 1 ? (
<div className={`h-2 ${data.colors[0]}`}></div>
) : (
<div className="flex">
<div className={`h-2 ${data.colors?.[0]} w-1/2`}></div>
<div className={`h-2 ${data.colors?.[1]} w-1/2`}></div>
</div>
)}The above code is not rendering any color, do I miss something ?
Answered by joulev
Dynamic class names don’t work due to class purging: https://tailwindcss.com/docs/content-configuration#dynamic-class-names. Follow the link to see why. For me I wouldn’t use tailwind here but a style={…} prop
2 Replies
@Siberian Accentor typescript
function generateColors(count: number): string[] {
const colors: string[] = [];
for (let i = 0; i < count; i++) {
const color = Math.floor(Math.random() * 16777215).toString(16);
colors.push(`bg-[#${color}]`);
}
return colors;
}
const arrayOfColors = [
{
id:"1",
data:{
colors: generateColors(1),
}
},
{
id:"2",
data:{
colors: generateColors(1),
}
}
]
// rest of the code
{data.colors?.length === 1 ? (
<div className={`h-2 ${data.colors[0]}`}></div>
) : (
<div className="flex">
<div className={`h-2 ${data.colors?.[0]} w-1/2`}></div>
<div className={`h-2 ${data.colors?.[1]} w-1/2`}></div>
</div>
)}
The above code is not rendering any color, do I miss something ?
Dynamic class names don’t work due to class purging: https://tailwindcss.com/docs/content-configuration#dynamic-class-names. Follow the link to see why. For me I wouldn’t use tailwind here but a style={…} prop
Answer
Siberian AccentorOP
@joulev Yeah, I used style={} and worked! Thanks