Using variables with Tailwind arbitrary values is not supported

Why is it that in tailwind, bg-[#5ad0a1] works but assigning the hex value to a variable such as const color = '#5ad0a1';, and then using bg-[${color}] does not work?

<span className={`inline-flex items-center rounded-md bg-[${color}] px-2 py-2 text-md font-base text-[${color}]`}>
 {params?.value}
 </span>

Answer №1

According to the documentation on Tailwind's website:

An important thing to note about how Tailwind extracts class names is that it will only recognize classes that are complete and unbroken strings in your source files.

If you try using string interpolation or combining partial class names together, Tailwind will not be able to identify them and therefore will not generate the relevant CSS:

Therefore, if you do this, Tailwind won't detect the classes:

<span className={`bg-[${color}] text-[${color}]`}>
      {children}
</span>

The recommended approach is to map your props to fixed class names:

const colorVariants = {
  bg: "bg-[#5ad0a1]",
  text: "text-[#5ad0a1]"
};

return (
  <span
    className={`inline-flex items-center rounded-md ${colorVariants.bg} px-2 py-2 text-md font-base ${colorVariants.text}`}
  >
    Hello
  </span>
);

Answer №2

When working with Tailwind, it requires the actual color value (#5ad0a1) in order to generate the CSS code correctly. It doesn't convert it to HTML using JavaScript and then process the code. So, what Tailwind sees is always ${color} instead of #5ad0a1.

As a result, Tailwind may create something similar to this:

.bg-[${color}] {
  background-color: ${color};
}

If you want to experiment, you can utilize CSS variables.

Add the root CSS in your JS file or directly in your CSS:

:root {
  --main-color: #5ad0a1;
}

Then, in your class definition, you can use:

bg-[var(--main-color)]

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

Installing a React Native app onto a wireless router is a straightforward process that can greatly

I need assistance with installing a React Native application on a WIRELESS LAN CONTROLLER system similar to a captive portal. Query: What is the process for installing my application on this router? Is it feasible to install my application on that route ...

Maintaining the proportions of images in different screen sizes when resizing

I apologize if this question has already been addressed, but I have been unable to find a solution that works for my specific issue. My Gallery consists of a side list of available images in one section, which when clicked changes the image source in anot ...

Ways to showcase an alert or popup when clicking?

I am utilizing a date picker component from this site and have enabled the 'disablePast' prop to gray out past dates preventing selection. Is there a way to trigger an alert or popup when attempting to click on disabled days (past dates)? Any sug ...

Obtaining the XPath for a data table containing two td elements that can be simultaneously clickable

<div class="dataTables_scrollBody" style="position: relative; overflow: auto; height: 370px; width: 100%; min-height: 0px;"> <table id="offer_create" class="display article-list ranklist_drag table table-bordered dataTable no-footer" aria-describe ...

The alignment issue persists in HTML/CSS despite troubleshooting efforts

I am facing a challenge while attempting to center text within a modal window, despite my efforts the text remains uncentered. This is my HTML code: <div ng-init="modalCompassDir()"> <div class="myModal"> <img class='floor ...

What could be causing the high order component to fail in React?

I am having trouble with a high order component not functioning as expected. I'm attempting to display a button and label using the HOC. Here is my code: http://codepen.io/anon/pen/ygpVeZ var D = (comp) => class extends React.Component{ render ...

Is there a way to hide the row select option for individual rows in MUIDatatables without affecting the multiple row select options?

Is there a way to hide the checkbox in the header row that allows selection of all rows at once? I prefer to manually select multiple options by clicking on each individual row. Can the row select option be hidden? https://i.sstatic.net/dfiJQ.png ...

What sets apart the various useEffect functions in React?

useEffect(() => { return () => setTimeout(() => set_current_focus(index_map[comp_index]), 1000); }, [comp_index]); In addition, useEffect(() => { return setTimeout(() => set_current_focus(index_map[comp_index]), 1000); } ...

What is the best way to ensure that my search box is responsive in HTML and CSS while also horizontally centering the search_box div?

Question 1: I need assistance in making this search box responsive. Every time I try to adjust the screen width, the button ends up below the input field. How can I resolve this issue? Question 2: Is there a way to horizontally center the div class=" ...

What is the best way to incorporate an ASYNC function within a .map function to dynamically populate a table in a REACT application?

I am attempting to use the .map() method in REACT to call an async function and populate table data cells. The async function communicates with the backend of my application using data from the array being looped through. When called correctly, the functi ...

Using React along with Material-UI Date picker, managing it as an ISO string. Issue arises where the text input does not clear out when

When using Mui DatePicker and controlling the value as a string, I noticed that if I start typing in the text field but leave it as 01/MM/YYYY and then hit an external clear button that sets the controlled value to null, the text field is not cleared. How ...

Transform information from an array that consists of nested arrays to be utilized within a component

Recently, I retrieved a bulk of data from an API located at My goal is to integrate the coordinates into a React Leaflet component that can showcase markers on a map. <Marker position={[LAT, LON]} /> The data provided below contains coordinates as ...

When employing DIV instead of TABLE, the issue arises where the width of the DIV does not completely occupy

<div style="width:100%;"> <div style="background-image:url('../images/navi/top-red.png'); float:left;"></div> <div style="width:180px; float:left"><img src="/images/navi/logo.jpg" ...

Tips for creating a section that perfectly stretches to cover the entire view port in HTML

After browsing through this website, I was inspired by its design and wanted to replicate something similar. The unique approach they took to ensure each section fits 100% of the viewport caught my eye. They utilized a "div section-background" within each ...

I am facing an issue where HTML is not loading images or some parts of my CSS in PHP

I've been working on connecting my website to a MySQL database using PHP. Initially, I thought I could keep the HTML and CSS the same, but after adding everything, the images on the website stopped showing up as they did before. The fonts and other el ...

During the installation process of the react server, a directory is not found

const issue = binding.mkdir( ^ Problem: ENOENT: folder or directory does not exist, mkdir 'D:\interview tasks react\adwinreact' at Object.mkdirSync (node:fs:1373:26) at module.exports.makeDirSync (C:\U ...

Using ASCII 3D text can create a stunning visual effect on a website, but it can sometimes appear

My website is displaying ASCII 3D Text with glitchy lines, but this issue is not present on other websites. Example 1: Glitchy lines visible on my website Example 2: A different website using the same text without any glitchy lines. No glitches detected h ...

Performing a dynamic animation by toggling the class of an element with "classList.toggle" in JavaScript

I have been attempting to incorporate a fade animation using CSS when altering the class of the input and label elements within a form by utilizing the classList.toggle method in JavaScript. I'm puzzled as to why my code isn't producing the desir ...

What is the best way to bring in styles to a Next.js page?

I am facing an issue with my app where I have a folder called styles containing a file called Home.module.css. Every time I try to include the code in my pages/index.js, I encounter the same error message saying "404 page not found.." import styles from & ...

Discover the optimal method for integrating a Next.js CSR React application with Django and PostgreSQL

I have a question about developing a full-stack app. Currently, I am using a Next.js React app on the frontend and a Django app with a PostgreSQL database on the backend. There are two main approaches I have seen to integrate all of these components seaml ...