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"

`

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>
    </>
  );
}

This technique could be used for setting the theme of a component or site, similar to how the Tailwind CSS site does:

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

Swap out a component for another using a higher order component (HOC perhaps?)

I have noticed that certain libraries like "framer-motion" in react utilize this syntax, for instance to include an animated H1: <motion.h1> where the h1 tag is enhanced with animations specified in the component's props. What confuses me is ho ...

Responsive breakpoints in TailwindCSS seem to have an issue with applying padding and margin styles properly

Currently, I am tackling a project that involves creating a responsive design with Tailwind CSS on nuxtjs. Has anyone encountered the issue of py-8 applying to both breakpoints? If so, please share your insights! Here is how I have structured the compone ...

Turning a lambda function into a function that is compatible with next.js API: A step-by-step guide

I am currently using an Instagram API to retrieve data from my personal profile, which is triggered by a lambda function on Netlify. Here is a snippet of the code: require('isomorphic-unfetch') const url = `https://www.instagram.com/graphql/quer ...

Tips for navigating to reload page in NextJS following revalidation

I have a method that updates certain data. When updating, I need to revalidate the path, navigate to it, and reload the page to fetch new data. Here is what I tried: const path = `/app/homeworks/${res.slug}`; await revalidatePath(path); router.push(p ...

Bootstrap - the input group button is designed to align to the right side

Currently, I am in the process of constructing a navigation bar for a website that includes a search bar and a grouped button. Everything functions properly when viewed on a desktop, but as soon as I switch to mobile view and the collapsible menu is activa ...

What is the best way to position a bigger character directly above a smaller container?

My goal is to center a single character, using CSS, in a span that is smaller than the character itself. The setup I have is: <span id="A">X</span><span id="B">Y</span><span id="C">Z</span> All three spans are styled ...

Issues with changing background colors using Jquery animate

I am attempting to create a fading background color effect when a button is clicked. Currently, I can change the background color using this code: $("#" + lblqty).css("background","#e9f1ff"); However, when I try to use the animate function as shown below ...

Can you explain the mechanics behind Angular Component CSS encapsulation?

Is it possible to avoid CSS conflicts when using multiple style sheets? Consider Style 1: .heading { color: green; } And Style 2: .heading { color: blue; } If these two styles are applied in different views and rendered on a layout as a Partial Vi ...

IE7 is not applying the conditional CSS styles to content loaded through AJAX

I am currently tackling some challenges with IE7 compatibility in a Rails application that I am developing. It appears that CSS styles implemented from a stylesheet applied with a conditional comment are not being rendered properly when using HAML like thi ...

Maintain the visibility of the jQuery dropdown menu even when navigating to a different page within the

I am experiencing an issue with my dropdown menu. Whenever I click on a "dropdown link", it opens another page on my website, but the menu closes in the process. I want to ensure that the menu stays open and highlights the clicked "dropdown link" in bold. ...

What is the process to create a sticky Material UI grid element?

Currently, I am in the process of developing the front-end for a shopping cart. To organize the content, I have split the container into two columns using Grid container and Grid item. In each column, various components are placed - the left side containin ...

The implementation of useState is not functioning properly when used within a parent useState function

I am currently working with a Ticket child class where I set the total amount after changing the number of tickets. The issue I am encountering is that the setNumber function doesn't seem to work properly unless the setTotal function is commented out. ...

Issue with Server Sent Events: Error message net::ERR_INCOMPLETE_CHUNKED_ENCODING 200 is preventing proper functionality

I've been working on implementing server-sent events using the code below (nodejs+express for backend and React for the frontend). However, I am facing an issue where the onmessage event is not triggering when I try to update the count through the ter ...

How can I append a query parameter to the URL in NextJS?

My goal is to include a query parameter whenever I enter some text in an input field and press the ENTER key. However, I'm struggling to determine the correct placement for this query parameter to function properly. Essentially, I want my URL to show ...

Encountering an ENOENT error while attempting to incorporate a style guide into next.js (react)

Recently, I delved into learning next.js and decided to enhance my project with documentation using To kickstart my project, I utilized npx create-next-app After installation and configuration setup, I added the following code snippet: [styleguide.config ...

Drag and drop surprise: When items are dragged onto the screen, a magical box will appear. But watch as the box disappears when the item is dragged

I am a newcomer to knockout JavaScript and am currently utilizing Knockout drag and drop functionality in my project. Initially, I have two divisions - one is visible while the other has a display property set to none. During the drag enter function, I wan ...

Remove the empty space between lines of images

Is there a way to remove the horizontal and vertical space between the squares? <div class="first"> <ul> <li><img src="http://dummyimage.com/40x40/111111/000000.jpg"/></li> <li><img src="http://dummyimage ...

Combining NodeJS and ExpressJS to deliver a unified JavaScript file when in production mode

Currently, I am managing multiple individual JS files in the following way: <script defer src="/js/libs/jquery.min.js"></script> <script defer src="/js/libs/plugins.js"></script> <!-- application core --> <script defer sr ...

Typed NextJs navigation to a specific route

<Link href="/about"> <a>About Us</a> </Link> Is there a way to ensure type safety with NextJs links? Currently, it is challenging to restructure the Link component as it is just a string. I stumbled upon this repos ...

Sometimes the Navbar options fail to show up consistently on the Navbar bar

I recently launched my website at campusconnect.cc Unfortunately, I've noticed that when resizing the window, the navbar options are shifting up and down. Can anyone help me identify the issue and provide guidance on how to resolve it? ...