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?
CodePudding user response:
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} />
CodePudding user response:
You can render classes conditionally with a library like clsx. Then your child component would render:
<div className={clsx(
"border-blueGray-400 bg-blueGray-50 text-blueGray-700": props.color === "blueGray",
"border-mGray-400 bg-mGray-50 text-mGray-700": props.color === "mGray",
)} />
This is not a good solution if you just want to modify one or two attributes. I would then advise to pass tailwind classes as props directly instead, like mentioned in the other answer.
But if you have some more complex logic, like multiple css attributes depending on the class, this solution might be good.