I have a React app that uses Tailwind CSS and multiple themes.
index.css:
@tailwind base;
@tailwind components;
@tailwind utilities;
@layer base {
[data-theme='default'] {
--color-primary: #008cba;
--color-secondary: #e7e7e7;
--color-success: #4caf50;
--color-danger: #f44336;
}
[data-theme='secondary'] {
--color-primary: #af8ffa;
--color-secondary: #e7e7e7;
--color-success: #4caf50;
--color-danger: #f44336;
}
}
@layer components {
.btn-primary {
background-color: theme(colors.primary);
color: theme(colors.danger);
}
.btn-secondary {
background-color: theme(colors.secondary);
color: black;
}
.btn-success {
background-color: theme(colors.success);
}
.btn-danger {
background-color: theme(colors.danger);
}
}
tailwind.config.js:
/** @type {import('tailwindcss').Config} */
export default {
content: ['./index.html', './src/**/*.{js,ts,jsx,tsx}'],
theme: {
extend: {
colors: {
primary: 'var(--color-primary)',
secondary: 'var(--color-secondary)',
success: 'var(--color-success)',
danger: 'var(--color-danger)',
},
},
},
plugins: [],
};
I defined a simple button component that takes a variant ('primary' | 'secondary' | 'success' | 'danger') as a prop:
import { ButtonProps } from './Button.types';
function Button({ variant, children, ...rest }: ButtonProps) {
return (
<button
className={`border-none py-2 px-4 text-center inline-block text-md border-r-4 cursor-pointer btn-${variant}`}
{...rest}>
{children}
</button>
);
}
export default Button;
The problem is that the custom .btn- classes, like .btn-primary, don't get applied consistently. Most of the time they won't render, however if while the app is loaded I change the btn class and I hardcode something btn-primary then the styles load fine. After that I can change it back to btn-${variant} and the styles load fine. At this point I can also change the styles in index.css and the new styles also get applied.
As a side note, when they don't get rendered they won't even show in the styles tab in google developer tools. If I inspect the element the class is there, but the styles don't show in the styles tab.
I don't really know what I'm missing here.
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>
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments