I'm having the following noob issue trying to assign dynamically tailwind classes to a react component.
I have extended my theme colors in the tailwind.config.js as follow:
...
theme: {
extend: {
colors: {
blueGray: {
50: '#f6f9f9',
100: '#e4f1f8',
200: '#c2e0f0',
300: '#91c0db',
400: '#5b9bbf',
500: '#4479a3',
600: '#385f87',
700: '#2d4768',
800: '#203049',
900: '#131d2f',
},
// OTHER COLORS
},
},
},
...
My react component looks like this:
import Draggable from 'react-draggable';
type SensorProps = {
name: string
color: string
}
export default function Sensor(props : SensorProps): JSX.Element {
return (
<Draggable
axis="both"
bounds="flow-canvas">
<div className={`border-${props.color}-400 bg-${props.color}-50 text-${props.color}-700`}>
<p> {props.name} </p>
</div>
</Draggable>
)
}
This are some examples of how I instantiate my Sensor component
<Sensor name={"Water Level"} color={"blueGray"} />
<Sensor name={"Flow"} color={"mGreen"} />
The problem is that the classes are not applied, but when I inspect my page the div has the right classes.
If switch from:
<div className={`border-${props.color}-400 bg-${props.color}-50 text-${props.color}-700`}>
to:
<div className={`border-blueGray-400 bg-blueGray-50 text-blueGray-700`}>
It works :(
I'm already using the tailwind JIT compiler
...
mode: 'jit',
purge: ['./pages/**/*.{js,ts,jsx,tsx}', './components/**/*.{js,ts,jsx,tsx}'],
...
Any suggestions?
The tailwind compiler parses your code on compilation and purges classes that it does not see used anywhere. You're not using border-blueGray-400 directly so it treats it as an unused class and removes it from its bundle to improve performance.
The best solution in my opinion is to not pass arbitrary props like color, size etc., but instead pass a className attribute.
Therefore, you would render your component like this:
<Sensor className="border-blueGray-400 bg-blueGray-50 text-blueGray-700" />
And in the child component:
<div className={props.className} />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With