Quirks in TailwindCSS template literals behavior

Looking at this specific component:

const SaleBadge = ({ textContent, badgeColor }) => {
    return (
        <Badge className={`bg-${badgeColor}-200 hover:bg-${badgeColor}-300 animate-pulse align-middle ml-2`} variant="secondary"><Percent className="w-4 mr-2" />{textContent}</Badge>
    )
}

The issue arises when trying to set the background color of the Badge based on the template literal and the "badgeColor" prop. Strange results are being produced.

For example, changing the value from "-200" to "-300" causes no background color to appear, almost as if an invalid color is being passed. However, if a fixed color like "violet-300" is used initially, then switching back to using "badgeColor" works perfectly fine. Any thoughts on why this might be happening?

It's unclear whether this behavior is intended or not, as it seems that template literals are somewhat functioning in this context.

An attempt was made to address this issue by creating a function that generates the className string, but the problem continues:

const SaleBadge = ({ textContent, badgeColor }) => {

    function returnBadgeClassName() {
        return(
            `bg-${badgeColor}-500 hover:bg-${badgeColor}-300 animate-pulse align-middle ml-2`
        )
    }

    return (
        <Badge className={returnBadgeClassName()} variant="secondary"><Percent className="w-4 mr-2" />{textContent}</Badge>
    )
}

Answer №1

According to the guidelines:

A key point to note about how Tailwind interprets class names is that it will only recognize classes that are present as complete uninterrupted strings in your source code.

If you use string interpolation or combine partial class names, Tailwind will not identify them and thus will not produce the corresponding CSS:

Avoid constructing dynamic class names

<div class="text-{{ error ? 'red' : 'green' }}-600"></div>

In the scenario above, the strings text-red-600 and text-green-600 do not match exactly, so Tailwind will not create those classes. Ensure that all class names used are complete:

Use complete class names at all times

<div class="{{ error ? 'text-red-600' : 'text-green-600' }}"></div>

Hence, creating bg-${color}-500 won't work. Instead, try this:

        <Badge className={`${badgeColor === "red" ? "bg-red-500" : badgeColor === "green" ? "bg-green-500" : "bg-blue-500"}animate-pulse align-middle ml-2`} variant="secondary"><Percent className="w-4 mr-2" />{textContent}</Badge>

Alternatively, consider passing the color as a prop to the component and handling the logic inside the component itself

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

Ajax encountered a problem while attempting to download the file

I have a situation where JavaScript generates content within a function, and I need to save that content in my downloads folder. However, when I attempt to do so via AJAX, it does not work and no errors are being displayed. Here is the JS code: $.ajax({ ...

Implementing dynamic content updating in WordPress by passing variables and utilizing AJAX

Currently, I am working on a shopping page that displays a list of all the stores. To streamline the user experience, I have created a sidebar containing various categories and implemented pagination within the store listings. These lists are generated thr ...

Next.js Adsense Ad Units

I am seeking assistance with incorporating Adsense ad units into nextjs. I have already implemented the auto-generated ads successfully, but I would like to customize them further. This is what I have done so far, but I am unsure if it is the optimal appro ...

The custom font fails to load on a customized Material UI theme

In my React web application, I tried to implement a custom font by writing the following code: import React, { FunctionComponent } from 'react' import { createMuiTheme, MuiThemeProvider } from '@material-ui/core/styles' import SofiaPro ...

The Owl-Carousel's MouseWheel functionality elegantly navigates in a singular, seamless direction

Issue at Hand: Greetings, I am facing a challenge in constructing a carousel using Owl-Carousel 2.3.4. My goal is to enable the ability to scroll through my images using the mousewheel option. Code Implementation: Incorporating HTML code : <div style ...

"Phraseapp is in the process of refreshing the primary language document

I currently have a locale file that contains various text keys that need to be translated. Each key corresponds to a specific text that needs to be translated into different languages: { key1: "Text to translate", key2: "Another text to translate", ...

How to make a JQuery list item unselectable when appending it

I encountered a strange issue while using jQuery to append items to a list. <ul id="idNicheItems" class="clScrollItems ui-widget-content ui-corner-all"> <li id="NicheItem_1"> Item 1</li> <li id="NicheItem_2"> Item 2</li& ...

Achieve resumable uploads effortlessly with google-cloud-node

While this code works well for regular uploads, I am curious about how the resumable upload feature functions when a user loses connection during a large upload. Does simply setting 'resumable' to true in the writeStream options make it work effe ...

Throttle individual users, exclude frontend server and getServerSideProps from throttling

Currently, I am working on an application using NestJs where I've implemented the throttle module to prevent abusive requests. One aspect that has left me puzzled is whether implementing a block for abusive requests (e.g., exceeding 20 requests per m ...

Steps to access arrays that are embedded in a file and are loaded asynchronously

https://gyazo.com/e80eea9f69c0cbb52cc7929d0a46ea2f The name of the object is totalCount. How can I retrieve the count from it? Object.result was my first attempt, but it returned undefined. For my second attempt: var count = totalCount.resu ...

Executing functions and setting element values upon loading in Javascript

I am currently working on updating a small Javascript function that assigns an active class to the parent <div> of a group of radio buttons when the page loads and also when there's a change event. The existing function looks like this: functi ...

Save log discrepancies to a document

Upon completing my website for graduation, there is still one important feature I want to add. I would like to implement a script that sends the name of the website where it is installed, as well as any error messages, to my website. For instance: The fol ...

Is there a way to share another person's contact card using whatsapp-web.js?

Is it possible to send a contact card of someone else using whatsapp-web.js, even if the person is not saved in my phone's contact list? I want to send a contact card to someone who is on my phone's contacts, but the contact information I want to ...

Error: Trying to access 'product-1' property on an undefined object

Having trouble displaying JSON data in my React.js project, I've been stuck on an error for the past couple of days with no luck in solving it. The JSON data is stored in a file named products.json: { "product-1": [ { ...

A function similar to setCell for modifying form fields in JqGrid

After searching through numerous answers from @Oleg, I couldn't find the solution I was looking for. I am dealing with a grid where I can edit inline in certain fields. Specifically, I am working with autocomplete functionality and when I select an it ...

The alpha value returned by gl.readPixels in Three.js will consistently be 255

Is there a way to retrieve pixel values from a threejs application? const gl = renderer.context; const currentFrame = new Uint8Array(gl.drawingBufferWidth * gl.drawingBufferHeight * 4); // read image data from gl gl.readPixels(0, 0, gl.drawingBufferWidth ...

Is the ID "nodeName" specifically designated as reserved in the HTML5 language specifications?

I have an element with the following id: <span id="nodeName"></span> In my HTML code. Then, when using jQuery to do the following: $("#nodeName").html("someString"); I am getting an error in the console that says: Uncaught TypeError: Objec ...

How do I retype an interface from a dependency?

It's difficult to put into words, so I have created a repository for reference: https://github.com/galenyuan/how-to-retyping My goal is to achieve the following: import Vue from 'vue' declare module 'vuex/types/vue' { interfac ...

Obtaining essential data while facing a redirect situation

I need to extract the og data from a specific URL: https://www.reddit.com/r/DunderMifflin/comments/6x62mz/just_michael_pouring_sugar_into_a_diet_coke/ Currently, I am using open-graph-scraper for this task. However, the issue I'm facing is that it i ...

Issue with jquery curvy corners not functioning properly on Internet Explorer 8

Check out my website at If you view the page in IE8 and then in IE7 compatibility mode, you'll notice a strange issue. The box on the right disappears in IE8 but displays perfectly rounded corners in IE7. I am currently using the jQuery Curvy Corner ...