What is causing the absence of the tailwind dynamic class?

I am currently using the latest versions of Next.js and Tailwind CSS. Below is my Tailwind config:

module.exports = {
    mode: "jit",
    content: [
        "./pages/**/*.{js,ts,jsx,tsx}",
        "./components/**/*.{js,ts,jsx,tsx}",
    ],
    theme: {
        extend: {},
    },
    plugins: [],
};

Within the components folder, I have a component named Test.js which contains the following code:

const colors = {
    orange: "bg-orange-100",
    blue: "bg-blue-100",
};

export default function Header() {
    function HeaderButton(props) {
        return <div className={`bg-red hover:${colors[props.color]}`}></div>;
    }
    return <HeaderButton color="orange">Test</HeaderButton>
}

The issue I am facing is that although the bg-red class is present, when it is hovered over, the class bg-orange-100 is applied but is not reflected in the final CSS output. What could be causing this?


Upon further investigation, I have discovered that the problem lies specifically with the hover functionality. Adding regular class names works fine, but modifiers like hover do not work as expected.

Answer №1

According to the tailwind documentation found at , it is advised not to generate classes dynamically as you have done.

It is important to realize that tailwind interprets your class definitions during compile time, so a clear declaration is essential for tailwind to understand your intentions at runtime.

Consider the following simple example for better understanding:

<div className={`mt-[${size === 'lg' ? '22px' : '17px' }]`}></div>
// Tailwind does not know how to build the class
<div className={ size === 'lg' ? 'mt-[22px]' : 'mt-[17px]' }></div>
// Tailwind understands 'mt-[22px]' and 'mt-[17px]' to create the appropriate classes

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

Storing files in MongoDB to ensure no duplicates are saved

I'm currently working on a project where I need to save multiple documents in mongodb using mongoose. Additionally, I want to make sure that no duplicates are saved. Here is the function I have implemented: const Stock = require('./models/stock&a ...

Combining Nextjs and Expo in a Monorepo may result in the error message "Invalid Hooks Call."

I have organized a monorepo with 4 different packages as follows: . ├── lerna.json ├── package.json ├── packages │ ├── admin-> Basic CRUD for backend with Nextjs │ ├── mobile-> Expo app │ ├── server-> ...

Executing a function after an AngularJS directive's reference function has been called

<CustomDirective customValue="someValue" anotherFunctionRef="anotherFunction()"></CustomDirective> angular.module('AppName', ['OtherDependencies']). directive('CustomDirective', ...

The animation does not reoccur in Firefox when using Modal

I have a unique issue with my modal that displays images, where the animation only works the first time on Firefox. When I open the modal for the first time, everything works perfectly, but if I close it and then reopen it, the animation no longer plays. I ...

Encountering an error in Node JS while attempting to utilize the Formidable package

I am currently studying the Node.js Comprehensive Guide textbook. Encountered an issue while trying to utilize the "Formidable" package for handling form uploads, triggering an error const form = new formidable.IncomingForm(); ^ Type ...

How to pass a method from a child component to a parent component in Vue.js

Does anyone know how to pass a function from the child component to the parent component? I have a modal in the parent component with cancel and submit buttons. When either button is clicked, I want to close the child component. I tried setting "show" in t ...

Creating a dynamic background image for the ul/li div element

As a newcomer to website development, I am currently exploring how to dynamically set images in the ul/li elements within a div. Below is a snippet of the HTML code I have been working on: <div class="results"> <ul class="row"> < ...

Cannot use React's setState function

This element represents the main container: modifyData(){ this.setState({ modified: true }).bind(this) } I am passing it to a sub-element: <Profile updateData={this.modifyData} auth={this.props.auth} details={profile}/> The sub ...

Vue Dev Tools is not updating data in Ionic Vue 3

There seems to be an issue with the updating of Reactive and Ref data in Vue Dev Tools when changes are made in an input field bound with v-model within a form. The updated data is only visible when I interact with another component and then return to the ...

How can PHP effectively interpret JSON strings when sent to it?

When working with JavaScript, I am using JSON.stringify which generates the following string: {"grid":[{"section":[{"id":"wid-id-1-1"},{"id":"wid-id-1-4"}]},{"section":[{"id":"wid-id-1-5"}]},{"section":[{"id":"wid-id-1-2"},{"id":"wid-id-1-3"}]}]} I am ma ...

Update the nodes in a directed graph with fresh data

For the past few days, I've been facing a persistent issue that I just can't seem to find a solution for when it comes to updating nodes properly. Using three.js to render the graph adds an extra layer of complexity, as the information available ...

What could be the reason for my selector ( a:hover ~ a ) not functioning correctly?

My goal is to create a hover effect where hovering over a link will reduce the opacity of other links while keeping the color of the hovered link unchanged. I attempted using a:hover ~ a, but it did not work as expected. I set up a new jsfiddle with a bas ...

403 Forbidden error occurs when AJAX value %27 is triggered

Stack Overflow has seen a multitude of inquiries related to apostrophes in form fields, particularly concerning unencoded values. An insightful post sheds light on the limitations of using encodeURIComponent(str) for handling apostrophes and suggests crea ...

Activating a text field using a checkbox with JavaScript

Could you please provide guidance on how to toggle the editability of a text box based on the selection in a combo box? For instance, if the combo box value is set to 1, the text box should be enabled; if it's set to 0, the text box should be disabled ...

The Clash of Form Action and JavaScript

Can someone help me with this issue? I have a form and a script to trigger an alert message. The code I'm using is working well: <input id="autocomplete" class="input_message" type="text" name="message" autocomplete="off" placeholder="...typ ...

Tips for testing React Final Form's Field Components on a unit level

While developing a form component using the react-final-form library, I encountered a situation where the component started growing in size. To address this, I decided to split it into multiple sub-components - with the parent component containing the < ...

The input value may contain certain characters at any position

An issue has arisen with my directive that is meant to validate an input field to ensure it does not include the characters &, <, > .directive('refValidate', [function () { var regExp = /^[&\<\> ]*$/; return { ...

Using regular expressions, you can conveniently extract text that is contained within paragraph tags

I attempted to use RegExp in JavaScript to extract text between paragraph tags, but unfortunately it isn't working... Here is my pattern: <p>(.*?)</p> The text I am trying to extract from is: <p> My content. </p> <img sr ...

A foolproof method for confirming an object is an EcmaScript 6 Map or Set

Can someone help me verify if an object is a Map or Set, but not an Array? For checking an Array, I currently use lodash's _.isArray. function myFunc(arg) { if (_.isArray(arg)) { // doSomethingWithArray(arg) } if (isMap(arg)) { // doS ...

What options do I have for sorting through my inventory using the search feature?

Having some trouble setting up isotope filtering on my search bar. I have managed to get the Isotope function working on checkboxes, but for some reason, my search bar isn't functioning as expected. I found a solution online for filtering results bas ...