29

I am trying to set dynamic background colors using Tailwind.

However, the background color is not being applied to the div. I am confused because when I check the inspector, I can see that in the browser, the correct bg-${colors[index]} was applied to each div, but the color is not being rendered.

const colors = ['#7a5195', '#bc5090','#ef5675'] export default function App() { const names = ['Tyler', "Charles", 'Vince'] let labels = {} names.forEach((name,index)=>{ labels[name] = `bg-[${colors[index]}]` }) return ( <> { names.map((name)=>{ return( <div className={`${labels[name]}`}> {name} </div> ) }) } </> ); } 
1

6 Answers 6

45

in Tailwind you can't use dynamic class naming like bg-${color}.

This because when Tailwind compiles its CSS, it looks up over all of your code and checks if a class name matches.

If you want dynamic name classes you should write all the class name.

But for your specific use case, I would not use the JIT of Tailwind and instead use the style attribute and dynamically change the backgroundColor value.

It will use less CSS and also give you less headache.

Finally, this is my suggestion

const colors = ['#7a5195', '#bc5090','#ef5675']; export default function App() { const names = ['Tyler', "Charles", 'Vince'] const labels = {}; names.forEach((name, index) => { labels[name] = colors[index]; }); return ( <> { names.map((name) => ( <div style={{ backgroundColor: `${labels[name]}` }}> {name} </div> ) } </> ); } 
Sign up to request clarification or add additional context in comments.

3 Comments

For the use of dynamic values in the classes, I made a hidden div at the root, with another div inside with all class names that the dynamic functions will result in. It's a bad format, but you will use all the features of Tailwind like sm:, lg:, and others. Using the style attribute you can't use mediaqueries and other rich features of the Tailwind.
@SandroSantos you should look into Tailwind's safelist to prevent adding that hidden div at the root : tailwindcss.com/docs/content-configuration#safelisting-classes
Thank you so much!
6

You can also add classes to your safelist in your tailwind config.

// tailwind.config.js // Create an array for all of the colors you want to use const colorClasses = [ '#7a5195', '#bc5090', '#ef5675' ]; module.exports = { purge: { content: ["./src/**/*.{js,jsx,ts,tsx}", "./public/index.html"], // Map over the labels and add them to the safelist safelist: [ ...colorClasses.map((color) => `bg-${color}`) ], }, darkMode: false, // or 'media' or 'class' variants: { extend: {}, }, plugins: [require("@tailwindcss/forms")], }

This way you can use the colors that were included in the colorClasses array dynamically as they will not be purged.

Note: If you want to do bg-blue-500 for example, you'll need to include all of the color weights as part of the safelist (as well as add that color to the array).

...colorClasses.map((color) => `bg-${color}-500`) 

2 Comments

You can use regular expressions to safe multiple classes at once. See tailwindcss.com/docs/content-configuration#safelisting-classes
This should be the only valid answer
2

Dynamic Background Color in React Component with Tailwind CSS

I have a React component named VisitingCard where I want to dynamically set the background color based on a prop. Here's how I achieved it using Tailwind CSS:-

const VisitingCard = (props) => { // Destructuring props for ease of use const { colour, title, handle } = props; // Object mapping color prop to Tailwind CSS background color classes const colorVariants = { green: 'bg-yellow-500', yellow: 'bg-red-400', blue: 'bg-blue-500' }; return ( <> <div className={`w-40 h-20 border ${colorVariants[colour]}`}> <div>Title: {title}</div> <div>Handle: {handle}</div> </div> </> ); } export default VisitingCard; 

In this component, I use an object colorVariants to map color prop values to corresponding Tailwind CSS background color classes. This allows for dynamic styling based on the color prop passed to the component.

Now, when you use the VisitingCard component like this:-

<VisitingCard colour="green" title="John Doe" handle="@john_doe"/> 

It will render a div with a green background, and you can easily extend the colorVariants object with additional colors as needed.

Comments

2

According to https://tailwindcss.com/docs/adding-custom-styles:

<div class="bg-[#bada55] text-[22px] before:content-['Festivus']"> <!-- ... --> </div> 

I successfully achieved the goal strictly with "#bada55" and no other options, such as red (#FF0000) and others.

1 Comment

If the primary variants were set before, on the "tailwind.config" file, does it work with bg-primary-[${colorNumber}]?
0

I think easiest think is to use style attribute.

const [variantColor, setVariantColor] = useState<string | undefined>(""); const colorOptions=["#00FFFF","#FAEBD7","#DC143C"] {colorOptions?.map((color) => { return ( <div key={index} style={{ borderStyle: "solid", borderColor: variantColor === color ? `${color}` : `${color}50`, }} > <div onClick={() => setVariantColor(color)} style={{ backgroundColor: variantColor === color ? `${color}` : `${color}50`, }} /> </div> ); }) ); })} 

Comments

-7

Try this code

className={`bg-[${color}]`} 

1 Comment

2024 update: Despite the downvotes, this does work! See the documentation here tailwindcss.com/docs/adding-custom-styles. Make sure to use square brackets and a # before the color.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.