In Next.js, I am experiencing an issue where the Tailwind class is being added, but the corresponding

I'm currently in the process of developing a board game where I need to track players and their positions on specific squares. My goal is to display a small colored dot on the square where each player is positioned.

Here's a snippet of my template code:

<div className="board">
  {board.map((val, idx) => {
    return (
      <div className="row" key={idx}>
        {val.map((block) => {
          return (
            <div className="block" key={block!.index}>
              {block!.index}
              <div className="player-dots">
                {players.map((player: PlayerType) => {
                  if (player.currentSquare === block!.index) {
                    let colorClass: string = `bg-player${player.id}color`;
                    return (
                      <div
                        className={`h-3 w-3 rounded-full ${colorClass}`}
                        key={player.id}
                      ></div>
                    );
                  }
                })}
              </div>
            </div>
          );
        })}
      </div>
    );
  })}
</div>;

Below is the tailwind configuration:

const config: Config = {
  content: [
    "./src/pages/**/*.{js,ts,jsx,tsx,mdx}",
    "./src/components/**/*.{js,ts,jsx,tsx,mdx}",
    "./src/app/**/*.{js,ts,jsx,tsx,mdx}",
  ],
  theme: {
    extend: {
      backgroundImage: {
        "gradient-radial": "radial-gradient(var(--tw-gradient-stops))",
        "gradient-conic":
          "conic-gradient(from 180deg at 50% 50%, var(--tw-gradient-stops))",
      },
    },
    colors: {
      midnight: "#121063",
      primary: "#3A0CA3",
      secondary: "#4361EE",
      tertiary: "#4CC9F0",
      rose: "#F72585",
      grape: "#7209B7",
      white: "#ffffff",
      player1color: "#FF0000",
      player2color: "#0FA3B1",
      player3color: "#E072A4",
      player4color: "#3D3B8E",
    },
  },
  plugins: [require("@tailwindcss/forms")],
};
export default config;

It seems that the class is being added to the DOM, but the styles are not being applied as intended. Here is a screenshot for reference: https://i.sstatic.net/ekQqE5vI.png

I attempted to generate the class names dynamically within the className attribute, however, this approach did not yield the desired result.

Answer №1

To create dynamic classnames using Tailwind, refer to the documentation at https://tailwindcss.com/docs/content-configuration#dynamic-class-names.

To ensure all variants are included, either list them out completely without a string template or add any classes not generated to your Tailwind config safelist:

/** @type {import('tailwindcss').Config} */
module.exports = {
  content: [
    './pages/**/*.{html,js}',
    './components/**/*.{html,js}',
  ],
  safelist: [
    'bg-player1color',
    'bg-player2color',
  ]
  // ...
}

Answer №2

It seems like the issue you're encountering is because of the dynamic class that is being generated. The problem lies in TailwindCSS not supporting dynamic classes, as it only compiles the classes present in your code during CSS compilation.

Resolution 1: One effective approach would be to create your own custom CSS file and style the players based on your specific preferences.

Resolution 2: Another option to consider is creating a hidden div and inserting all the necessary TailwindCSS classes inside.

<div class="hidden bg-player1color"></div>

Although I don't recommend utilizing the second solution, it can still serve its purpose.

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

Guide on transmitting data between NextJS and MongoDB

I'm facing an issue where the data from a form is being sent to MongoDB as undefined using nextJS and MongoDB. NewPlayerPage component: const newPlayerPage = (props) => { console.log('props: ' + props); const handleAddPlayer = a ...

Utilize Sequelize's cascade feature within your application

I'm currently building a web application using sequelize and typescript. In my database, I have three tables: WfProjectObject, which is connected to WfProject, and WfStep, also linked to WfProject. My goal is to include WfStep when querying WfProject ...

How to manually close the modal in Next.js using bootstrap 5

Incorporating Bootstrap 5.2 modals into my Next.js application has been smooth sailing so far. However, I've encountered an issue with closing the modal window after a successful backend request. To trigger the modal, I use the data-bs-toggle="modal" ...

The Google Sign-in feature is unable to access the property 'load' due to being undefined

I'm currently working on implementing a Google Sign-in feature in an Angular application, but I'm encountering the following error: Cannot read property 'load' of undefined This was actually working perfectly just an hour ago, but n ...

Revise Swagger UI within toggle button switch

My project aims to showcase three distinct OpenApi definitions within a web application, enabling users to explore different API documentation. The concept involves implementing a toggle button group with three buttons at the top and the Swagger UI display ...

Issue with webpack dev server not correctly generating output files to be included in index.html

Struggling to configure webpack and react with typescript without the complexity of CRA. The dev server isn't outputting files to index.html for viewing in the browser. I want to maintain a clean and simple structure, avoiding the multiple js scripts ...

Exploring the potential of the forkJoin operator in Angular 4's Observable

I'm currently facing a challenge that involves retrieving both administrators and professionals from the "users" collection using AngularFire's latest version. I am utilizing Observables for this task. My goal is to make two parallel requests an ...

Contrasting Time To First Byte measurements between Chrome and Web Vitals

Discrepancies are apparent between TTBF values in the Chrome network tab and those logged by WebVitals. In an ideal scenario, these values should be identical, but there are instances where differences of 2-3 seconds are observed for specific cases. I am ...

Tips for retrieving input values when they are not available in HTML documents

In this code snippet, I am creating an input element with the file type without adding it to the DOM. My goal is to retrieve the value of this input once the user selects a file. Even though the input is not part of the HTML template, I still want to acces ...

Mastering the utilization of custom input events in PrimeNG with Angular

I am currently working on an Angular 16 project. Within this project, I have implemented a number input field that is being validated using formControls. To make my work more efficient, especially since this input is used frequently, I decided to encapsula ...

A better choice than Java's <? super SomeType> in Typescript

Is there a scenario in which one of the generic parameters used to create an instance of my class should be a superclass of another class? In Java, this is easily achievable using <? super SomeType>. What would be the equivalent in TypeScript? ...

Is there a function return type that corresponds to the parameter types when the spread operator is used?

Is it possible to specify a return type for the Mixin() function below that would result in an intersection type based on the parameter types? function Mixin(...classRefs: any[]) { return merge(class {}, ...classRefs); } function merge(derived: any, ... ...

What is the best way to modify an object within a pure function in JavaScript?

Currently, I am exploring different strategies to ensure that a function remains pure while depending on object updates. Would creating a deep copy be the only solution? I understand that questions regarding object copying are quite common here. However, ...

Utilizing Angular to import an SVG file from a backend and incorporate its content as a template

I am looking for a solution to load an SVG date from my Spring Boot backend and utilize it as an Angular template. Currently, the request is structured like this: getSVG (): Observable <any> { return this.http.get(`${environment.apiUrl}/path ...

Typescript throws an error when Redux useSelector fails to properly infer the state

Seeking guidance on how to access my state using the useSelector hook import { applyMiddleware, createStore } from 'redux'; import thunk from 'redux-thunk'; import { reducers } from './reducers'; export c ...

TS1057: It is required that an async function or method has a return type that can be awaited

There was a recent Github issue reported on March 28th regarding async arrow functions generating faulty code when targeting ES5, resulting in the error message: TS1057: An async function or method must have a valid awaitable return type You can find t ...

When deploying a Next.js application in a kubernetes environment, the resources may not be accessible

I have a Next.js application deployed in k8s. While the page is visible, it is unable to find js/css files. The error I receive in the browser console is posted below: https://i.stack.imgur.com/OjVoM.png Here is the docker file being used: FROM node:18-a ...

Next.JS does not support the application of nested CSS styles

I am currently facing an issue with Nextjs and sass(1.28.0). The nested css styles are not being applied on the webpage despite importing the css file as auth.module.scss without any errors. This project also involves AMP pages. Please let me know if there ...

Tips for managing the data type of a bound value through ngModel: preventing number distortion to string

I posted a query and managed to solve it. However, I observed that even though the provided data consists of objects defined like this: export interface GisPoint { e: number; n: number; } when a user inputs a value, the original content changes from { e: ...

What is the process for obtaining the access token generated by supabase authentication?

Currently utilizing Next.js 13 alongside Supabase v2, I have successfully generated an access token. However, the issue arises as the automatically created access token is not configured for the "localhost" domain, rendering it unreadable and inaccessible. ...