Reputation: 41
I am making a project in React using Tailwind CSS. I have to use a specific color and add border-{color}
, bg-{color}
, and more styles depending on a prop. I'm using the approach below but it doesn't work. Can someone help me here?
tailwindconfig.js
//tailwind.config.js
module.exports = {
theme: {
extend: {
colors: {
colorA: '#ff6d00',
colorB: '#33691e',
colorC: '#ffd600',
}
}
}
}
My components
function Component() {
const colors = ['colorA', 'colorB', 'colorC'];
return (
<>
<div className="m-3 h-20 w-20 bg-colorC">colorC</div>
{colors.map((color) => (
<ComponentColor
key={color} type={color} /*or-> type={`bg-${color}`}*/ />
))}
</>
);
}
function ComponentColor({ type }) {
const bgStyle = `bg-${type}`;
// const bgStyle = type;
return <div className={`m-3 h-20 w-20 ${bgStyle}`}>{type}</div>;
}
I understand that Tailwind is pre-rendered before it is loaded into the browser and only the classes used are bundled into the final style file. I can use a "safelist", but how could I handle the case where I have many colors and CSS properties?
//tailwind.config.js
module.exports = {
theme: {
extend: {
colors: {
colorA: '#ff6d00',
colorB: '#33691e',
colorC: '#ffd600',
}
}
},
safelist: ['bg-colorA', 'bg-colorB', ...],
}
Or there is a way to define the colors outside the Tailwind config and then call inside dynamically to generate the colors and safelist? Or perhaps some better method?
Upvotes: 1
Views: 827
Reputation: 7305
One quick solution is to pass the entire utility class to your ComponentColor
component. This way, the class is not built dynamically and will be picked up by Tailwind without needing a safelist.
You can then strip the "bg-" if you need to display the color name.
For example:
function Component() {
return (
<>
<div className="m-3 h-20 w-20 bg-colorC">colorC</div>
<ComponentColor colorClass="bg-colorA" />
<ComponentColor colorClass="bg-colorB" />
<ComponentColor colorClass="bg-colorC" />
</>
);
}
function ComponentColor({ colorClass }) {
const type = colorClass.substring(3);
return <div className={`m-3 h-20 w-20 ${colorClass}`}>{type}</div>;
}
Upvotes: 1