Unable to generate Tailwind CSS styles based on dynamic input values

Struggling to dynamically render Tailwind CSS properties, where the class is applied in the browser inspector but the color fails to change.

A function is utilized to take a rarity (tier) as input and output the corresponding Tailwind CSS property defining the color of that tier:

export function checkRarity(tier: string) {
  const rarityLookup = new Map([
    ["COMMON", "text-rarity-common"],
    ["UNCOMMON", "text-rarity-uncommon"],
    ["RARE", "text-rarity-rare"],
    ["EPIC", "text-rarity-epic"],
    ["LEGENDARY", "text-rarity-legendary"],
    ["MYTHIC", "text-rarity-mythic"],
    ["DIVINE", "text-rarity-divine"],
    ["SPECIAL", "text-rarity-special"],
    ["VERY_SPECIAL", "text-rarity-very-special"],
  ]);

  return rarityLookup.get(tier) || "bg-gray-400";
}

To combine manually defined properties with dynamic ones, twMerge and clsx are employed based on this resource.

The merging function is as follows:

export function cn(...inputs: ClassValue[]) {
  return twMerge(clsx(inputs));
}

Once the function is called to merge the Tailwind classes, like so:

const textColor = cn("text-2xl", checkRarity(auction.tier));

The className is then applied:

<h2 className={textColor}>
            {text}        
 </h2>

Attempts were made to resolve the issue by:

  • Verifying the spelling of Tailwind classes.
  • Ensuring the Tailwind classes are configured in the Tailwind file.
  • Experimenting with different names for the dynamic Tailwind class.

However, only the text-rarity-legendary Tailwind class seems to be functional.

Answer №1

When working with Tailwind, it’s important to note that there is no client-side runtime involved. This means that class names must be static and determined at build-time, rather than relying on dynamic values that may change on the client side.

If you encounter situations where dynamic styles are necessary, consider using inline styles like the example below:

export function checkRarity(tier: string) {
   const rarityLookup = new Map([
      ['COMMON', '#fff'],
      //...
   ]);

   return rarityLookup.get(tier) || '#fff';
}

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

utilizing the target attribute within a form to open the link in the current page

I have been working on a web application and implemented a drop-down menu using a form to display information about the selected category. However, I noticed that when an option is selected, the link opens in a new window instead of the same window. Below ...

What is the process for configuring a headless implementation of three.js on a node server, similar to the babylon.js-NulEngine setup?

My current project involves the development of a multiplayer three.js fps game, with client-side prediction in the browser. For the server-side implementation, I am utilizing Node.js Express.js and Socket.io for handling authoritative functions such as col ...

Unable to activate the 'Click' function in Angular/Typescript after selecting element with 'document.querySelector'

In my Angular 8 Project, there is an element on a page with a unique string attached to the attribute 'data-convo-id'. This element has a click function that loads data based on the data attribute specified above. However, without direct access ...

Is there a way to create a recurring Promise .then statement?

Is there a way to create a loop with a repeated .then clause? I need to continue executing the .then clause promise, and if the exit condition is not met, I have to repeat the same process until the condition is satisfied. My scenario involves making mult ...

Angular form submission results in receiving an object instead of a simple value

While building a basic Angular form, I am encountering an issue where instead of retrieving the form value upon submission using onsubmit, I am getting an object as the value. Side Note: I have included some sample code for reference. Could you please ad ...

Express JS form validation using hapi/Joi fails to accurately validate the input data in forms

I am currently facing an issue with my form validation using the hapi/Joi package. The problem is that the schema keys are all taking the value of "undefined", which results in the first validation error being returned. How can I resolve this issue? Additi ...

Issue with Accordion Panel Content Scroll Bar

Hello there, I've encountered a puzzling problem with my website. My objective is to insert a Time.ly Calendar widget into one panel of my accordion. On this page, "TOURNAMENTS: , the widget appears exactly as desired. However, when I replicate the c ...

Is it expected to conceal children who are 2 years old?

I came across the following HTML code snippet: <ul id="product_create-header" class="stepy-header"> <li id="product_create-head-0" class="stepy-active"> <div>Categoría</div><span>Categoría</span> </ ...

The issue of ERR_MODULE_NOT_FOUND in Node.js express.Router arises when attempting to import new routes

Something strange is happening. I was in the process of organizing my routes by creating a new folder. Within this folder, I used the express.Router API to define the routes and then exported the router itself. Here is an example code snippet from my pos ...

What is the best way to spy on a property being called within a function?

I am facing an issue where the 'offsetWidth' value is undefined and I need to spyOn it. The function getCurrentPage retrieves an element based on the id currentpage. Although spying on getCurrentPage works, I have been unable to declare the offs ...

I am trying to access the serial number data from an array of objects in ReactJS. Can anyone guide me

Is there a way to extract data from an array of objects, such as getting the serial number in ReactJS? In my current code snippet, I have an array called "number" with values [1, 2, 3]. My goal is to retrieve and display these numbers as a string like th ...

What would be the ideal technology stack (modules, frameworks) to use for delving into node.js and creating a successful first project that allows for learning and growth?

A year ago, I took my first small steps into the world of Node.js. Back then, I was overwhelmed by the sheer number of modules and frameworks available. Now, I am determined to dive deeper into the Node environment and kickstart a web-based project that wi ...

Tips for updating a nested MongoDB object

Looking to implement a reporting feature for my application When making a PUT request in the front end: .put(`http://localhost:3000/api/posts/report`, { params: { id: mongoId, ...

Discovering the maximum date using Mongoose in MongoDB

In my database, I have a 'users' collection where each user has a 'birthday' field represented as a javascript Date object. I am looking to use mongoose to query the 'users' collection and find the user with the oldest birthd ...

Steps for defining a function in AngularJS

I created a function and implemented it in the following manner: JavaScript : function updateInstitution (isValid) { alert('hi'); if (!isValid) { $scope.$broadcast('show-errors-check-validity', 'vm.form.institutio ...

Is there a way to hold off executing a JavaScript script until an XHR request is complete?

A script has been created for sending out a weekly newsletter using PHP. The PHP code is functioning perfectly, but there is also a script in place to keep track of how many newsletters have been sent to ensure all have been sent out. Here is the code: f ...

Creating a table that includes a textbox

Having some experience coding in php, I'm venturing into the world of js with a new project. My goal is to create a straightforward order form, where each line includes a text box for quantity, product name, and price. The price should be pulled from ...

the process of attaching an event listener to every item in a list and accessing them individually

When you click on an item in the list, it will switch the .done class on and off. <ul> <li class="bold red" random="23">Notebook <button>Delete</button></li> <li>Jello <button>Delete</button></l ...

Having trouble resizing a KineticJs group to 300x300?

Attempting to adjust the size of a kinetic group is resulting in an error message in JavaScript. The Kinetic JS documentation states that setSize should work with group nodes. ...

What is the process of transforming this jQuery script into AngularJS code?

Currently I am facing a situation where I am utilizing Angular1.x for a project. On a specific subpage, there are small clickable images along with some additional content below these images. The requirement is that only the images should be visible init ...