I’m trying to make custom button element using tailwind and react. I don’t know why when i’m apllying any color different then red it just doesn’t work.
I tried with many different colors and I really can’t find why it’s working only with red.
>Solution :
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-600andtext-green-600do 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
props.colorlikeexport default function Button(props) { const color = props.color; return ( <button className={`… ${color} …`} ><Button color="from-green-600 to-green-900 …"> -
Have a dictionary for
colorto Tailwind class names:export default function Button(props) { const color = props.color; const DICTIONARY = { red: 'from-red-600 to-red-900 …', green: 'from-green-600 to-green-900 …', // … }; // … return ( <button className={`… ${DICTIONARY[color]}`} > -
Use the
styleattribute for truly dynamic colors, ifthemecan be converted to a valid CSS color value (or you could get the color from Tailwind):export default function Button(props) { const color = props.color; const styles = { // Convert from `color` variable }; // … return ( <button className={…} style={style} > -
safelistthe classes, if you have a limited number of known colors:module.exports = { safelist: [ { pattern: /^from-(red|green|blue)-600$/ }, { pattern: /^to-(red|green|blue)-900$/ }, // … ], // … ];


