What is causing concatenated string class names to fail in Tailwind CSS?

Whenever I find myself needing to style my React elements, I end up using the style attribute instead of className. None of the examples I've come across seem to apply styles that fit my specific needs. Can you shed some light on why this happens and offer a solution?

I have gone through the documentation (https://tailwindcss.com/docs/content-configuration#dynamic-class-names), but my scenario involves allowing the user to choose a color from a color picker, and then updating the background accordingly. It's not practical for me to assign a separate "bg-[colorValue]" class for every possible color, so I resort to concatenating the value with "bg-[" afterwards. This is because I can't map all colors to full classnames.

const red500 = "red-500";
const red600Hex = "#dc2626";
const bgColor = "bg-[" + red600Hex + "]";
const bgColor2 = "bg-[" + "#dc2626" + "]";

function App() {
    return (
        <>
            <h1 style={{ backgroundColor: red500 }}>Hello</h1>
            <h1 style={{ backgroundColor: red600Hex }}>Hello</h1>
            <h1 style={{ backgroundColor: `[${red600Hex}]` }}>Hello</h1>
            <h1 style={{ backgroundColor: bgColor }}>Hello</h1>
            <h1 style={{ backgroundColor: bgColor2 }}>Hello</h1>
        </>
    );
}

Answer №1

Don't stress about string concatenation because Template literal strings work perfectly:

const red500 = 'red-500';
const red600Hex = '#dc2626';
const bgColor = `bg-[${red600Hex}]`;
const bgColor2 = `bg-[${'#dc2626'}]`;

export function App() {
  return (
    <>
      <h1 className={` bg-${red500} `}>Hello</h1>
      <h1 className={` bg-[${red600Hex}] `}>Hello</h1>
      <h1 className={` bg-${`[${red600Hex}]`} `}>Hello</h1>
      <h1 className={` ${bgColor} `}>Hello</h1>
      <h1 className={` ${bgColor2} `}>Hello</h1>
    </>
  );
}

Tailwind Playground

The link above also pointed out a warning regarding concatenation:

"Bug Finder: Unexpected string concatenation of literals.eslint"

`

https://i.sstatic.net/Q0j4W.png

Edit:

I extended the example to dynamically control the color of the last h1 with useState:

const colors = [
  {value: "#dc2626"},
  {value: "#dc06e6"},
  {value: "#dce606"},
]


export function App() {
  const [color, setColor] = React.useState(colors[0].value)
  return (
    <>
      <h1 className={`text-green-500 bg-${red500} `}>Hello</h1>
      <h1 className={`bg-[${red600Hex}] `}>Hello</h1>
      <h1 className={`text-green-200 bg-${`[${red600Hex}]`} `}>Hello</h1>`
      <h1 className={`${bgColor} `}>Hello</h1>
      <h1 className={`bg-[${color}]`}>Hello</h1>
      <select onChange={(e) => setColor(e.currentTarget.value)}>
        {colors.map(c => <option className={`bg-[${c.value}]`} value={c.value}>{c.value}</option>)}
      </select>
    </>
  );
}

https://i.sstatic.net/h3gkR.gif

This technique could be used for setting the theme of a component or site, similar to how the Tailwind CSS site does:
https://i.sstatic.net/BmCHy.png

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Which is more optimal for importing CSS - using the link tag or style tag?

Is this a matter of personal preference or is there a specific advantage to using one method over the other? <link href="main.css" rel="stylesheet" type="text/css"> versus <style type="text/css> @import url('main.css'); </style& ...

Error in JavaFX: CSS Parser anticipating COLON

Encountered an error and struggling to find the issue as everything seems right from my perspective: CSS Code: @font-face { font-family: 'Titillium'; font-style: normal; font-weight: normal; src: url('Titillium.ttf'); ...

Slideshow through each item using Typescript and Angular8

I came across a solution in this carousel on by one link, but I'm struggling to work with the jQuery code even though I have JQuery installed in my project. For example: const next = jQuery(this).next(); I am looking to convert the JQuery code from ...

Tips for customizing text field appearance in Safari and Chrome

I haven't had a chance to test it on IE yet. My goal is to create a unique style for the background image and text box shape, along with borders, for the search bar on my website, [dead site]. If you check it out on Firefox or Opera and see the sear ...

Loading Apollo GraphQL query

I have integrated Apollo GraphQL into my Next.js project to fetch posts and populate the content. Although the current code is functional, I am looking to enhance it by implementing the loading state of useQuery instead of the existing setup. This serves ...

Shift the image closer to the top of the sidebar next to the header

I am seeking to adjust the positioning of my circular image in the sidebar so that it aligns with my name in the header. The contact and tech skills sections may also require some tweaking. Although I have a grasp of the concepts of absolute and relative, ...

A guide on setting up Firestore rules using session cookies for secure authentication

For my next.js application, I incorporated session cookies using this guide. However, since there is no client user authentication, all firestore calls and permissions need to be managed within the server-side API. This brings up a question about the rele ...

Tips on aligning a span element at the center of an image without losing its mouseover

<div class="pic"> <img src="image.jpg" height="250"/> <span class="text" style="display:none">text here</span> </div> <scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </scrip ...

Chrome fails to load webfont upon page initialization

Encountering a problem with loading a WebFont specifically on Chrome version "48.0.2564.82 m (64-bit)". The issue arises from the webfont not being applied upon page load or navigation, unless I manually refresh the page. Below is the snippet of code fro ...

Tips for Incorporating HTML Code into an ASP Button's Text Attribute

How can I add a symbol to a button's text without it showing as blank? The symbol in question is an arrow, which you can find here. <asp:button id="btnAdd" runat="server" class="next"/> CSS: .next { content = &#10095; width:50px; } ...

How can I change the background color of the initial word in a textbox?

In my HTML, I have a text box input. While I am familiar with how to use CSS to set the background color of the entire textbox using background-color, I am wondering if it is possible to specifically target and change the background color of only the first ...

populate a bootstrap column with numerous span elements containing varying numbers on different rows

Wondering if it's possible to have a div with the bootstrap class "column" filled with multiple span elements that may break into more than one line. The challenge lies in making sure that each line of spans stretches and fills the line, even if there ...

Subpar mobile performance on a React/Next.js website

Can someone assist me with improving my website's loading times? While the desktop version has a pagespeed ranking of 99, the mobile version only ranks 75. Click here to view the report on pagespeed.web.dev What steps can I take to improve this? I a ...

Can one retrieve the CSS/XPath from a Capybara Element?

Is it possible to extract CSS/XPath from a Capybara Element? I have attempted to use #path but it doesn't appear to be effective. Here is the link I tried: The test is being executed on Selenium Webdriver. ...

Achieving perfect centering in PrestaShop using CSS for both horizontal

Hello there, I require assistance with aligning some images in the center of my Prestashop webpage. I am specifically struggling with aligning 3 circular images at the bottom of the page (not social icons). I cannot figure out how to properly center these ...

Adjust the position of an image to move it closer to the top using CSS

I have a fiddle where I am trying to adjust the position of an image (keyboard) to match a specific design. https://i.sstatic.net/flqCH.png In my fiddle, the keyboard image is slightly lower than the desired position shown in the design. I am looking for ...

What is the best way to implement CSS in a web application?

I've encountered an issue where the CSS styles are not applying when I add my web app to the home screen of an iPhone and launch the app using a shortcut icon. To illustrate, consider the following examples. First, opening the app with Safari. Below ...

Customer uploaded an image to the WordPress header but it is not aligning correctly

Trying to align an image added by my client in the WordPress header. As someone who is still learning CSS, I'm struggling to get it exactly where we want it. Visit the site here The Options House graphic currently sits on the right. My goal is to ha ...

Create a layout with two rows of two buttons in HTML aligned to the right side while maintaining the left side's

I am currently working on designing a menu for my webpage that includes four buttons. My goal is to have two buttons displayed at the top of the page and two buttons displayed at the bottom. To achieve this, I have written the following CSS code: .navButt ...

How to adjust the size of a div based on its child content, including margins

I have encountered an issue with animating the height of a configurable content div, which typically contains paragraphs of text. Shown below is my animation (slowly paced), starting from a height of 0 and expanding to its calculated height based on its c ...