I'm having trouble understanding why the blue color is not working in my component. Could you please help me troubleshoot this issue on Stack Overflow? I have a Tag component that should apply different background and text colors based on the color prop provided. However, when I set the color prop to "blue", the expected blue color is not being applied to the component. I have tried various solutions, including dynamically constructing the class names and using the correct syntax for Tailwind CSS classes. However, I have been unsuccessful in resolving the issue. Any guidance or suggestions would be greatly appreciated. Thank you in advance for your assistance!
import React from "react";
export default function Tag({ index, tag, color = "red" }) {
return (
<li
key={index}
className={`inline-flex items-center rounded-full px-3 py-2 text-xs font-bold uppercase bg-${color}-200 text-${color}-700`}
>
<a href={`/?=${tag.text.replace(/\s/g, "_").toLowerCase()}`}>
{tag.text}
</a>
</li>
);
}
As per the documentation:
The most important implication of how Tailwind extracts class names is that it will only find classes that exist as complete unbroken strings in your source files.
If you use string interpolation or concatenate partial class names together, Tailwind will not find them and therefore will not generate the corresponding CSS:
Don’t construct class names dynamically
<div class="text-{{ error ? 'red' : 'green' }}-600"></div>
In the example above, the strings
text-red-600
andtext-green-600
do not exist, so Tailwind will not generate those classes. Instead, make sure any class names you’re using exist in full:Always use complete class names
<div class="{{ error ? 'text-red-600' : 'text-green-600' }}"></div>
You could:
Have the entire class in the variable you pass to className
like
export default function Tag({ index, tag, color = "bg-red-200 text-red-700" }) {
return (
<li
key={index}
className={`… ${color}`}
>
Have a dictionary for color
to Tailwind class names:
export default function Tag({ index, tag, color = "red" }) {
const DICTIONARY = {
red: 'bg-red-200 text-red-700',
// …
};
// …
return (
<li
key={index}
className={`… ${DICTIONARY[color]}`}
>
Use the style
attribute for truly dynamic colors, if theme
can be converted to a valid CSS color value (or you could get the color from Tailwind):
export default function Tag({ index, tag, color = "red" }) {
const styles = {
// Convert from `color` variable
};
// …
return (
<li
key={index}
className="…"
style={style}
>
safelist
the classes, if you have a limited number of known colors:
module.exports = {
safelist: [
{ pattern: /^text-(red|green|blue)-700$/ },
{ pattern: /^bg-(red|green|blue)-200$/ },
// …
],
// …
];