The classes from TailwindCSS being passed as props in Next.js are not displaying properly when used within a map

const DummyData = [
  {
    _id: 1,
    title: "lorem ipsum",
    desc: " ",
    cta: "Explore Service",
    ctaUrl: "/",
    theme: "#E4F8ED",
    btnTheme: "#4F9D73",
    links: [
      {
        title: "Project lorem ipsum Tools ",
        url: "/",
      },
      {
        title: "Augmented lorem ipsum ",
        url: "/",
      },
      {
        title: "lorem ipsum and Forecasting ",
        url: "/",
      },
      {
        title: "Data lorem ipsum Analytics ",
        url: "/",
      },

      {
        title: "Quality Control lorem ipsum Analysis  ",
        url: "/",
      },
    ],
  },
  // more data
]

// jsx

<div className="text-left w-full bg-amber-100 mb-5 mx-auto   grid grid-cols-1 sm:grid-cols-3">
  {DummyData.map((item, index) => (
    <div className={`bg-[${item.theme}] p-5`} key={item._id}>
      <div className="p-4 h-full flex flex-col justify-between">
        <div>
          <p className="text-[#101828] font-bold text-[30px] leading-[36px]">
            {item.title}
          </p>
          <p className="text-[#101828] text-[12px] font-normal my-4 leading-[18px]">
            {item.desc}
          </p>
        </div>
        <div>
          <ul className="my-8">
            {item.links.map((list, index) => (
              <li
                key={index}
                className=" border-b-[1px] w-fit border-[#DBDBDB] py-2 "
              >
                <Link
                  href={list.url}
                  className="text-[#101828] text-[14px] font-medium leading-[22px] w-fit  flex transition-all hover:opacity-75  "
                >
                  {list.title}
                </Link>
              </li>
            ))}
          </ul>
          <Link
            href={item.ctaUrl}
            className={`text-[#fff] text-[14px] font-medium leading-[22px] w-fit py-2 px-8 flex transition-all hover:opacity-75  bg-[${item.btnTheme}]`}
          >
            {item.cta}{" "}
            <Icon
              path={mdiArrowTopRight}
              style={{ marginLeft: "0.5em" }}
              size={1}
            />
          </Link>
        </div>
      </div>
    </div>
  ))}
</div>

Having trouble with some CSS classes not rendering properly for buttons at times? Wondering why this happens and how to fix it? Is there a better approach to achieve this functionality? View the attached image for reference below. The button backgrounds in the automation and document understanding card are not displaying correctly, unlike the speech & language card. https://i.sstatic.net/EOrNn.png

Spent an hour looking through the code.

Answer №1

According to the guide:

The key takeaway from Tailwind's class name extraction process is that it will only recognize classes that are complete and unbroken in your source files.

If you try to dynamically construct or concatenate partial class names, Tailwind will not be able to identify them and will not generate the corresponding CSS:

Avoid creating dynamic class names

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

In the given example, the classes text-red-600 and text-green-600 are incomplete, so Tailwind will not create those classes. Instead, ensure that the class names you use are complete:

Stick to complete class names

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

You may consider using the style attribute like this:

<div className="p-5" key={item._id} style={{ backgroundColor: item.theme }}>
<Link
  href={item.ctaUrl}
  className="text-[#fff] text-[14px] font-medium leading-[22px] w-fit py-2 px-8 flex transition-all hover:opacity-75"
  style={{ backgroundColor: item.theme }}>

Answer №2

It appears that the class is being added correctly within the HTML, but it seems to not be functioning as expected. This could be due to Tailwind requiring knowledge of which classes are actively being used. Therefore, any classes used elsewhere in the code may work, while others do not.

If you wish to continue using this concatenation method, it is necessary to include all potential classes in the Tailwind safelist. Within the tailwind.config.ts (or .js) file, you can add them like so:

import type { Config } from 'tailwindcss'

const config: Config = {
  // other existing configs
  safelist: [
    'bg-[#4F9D73]',
    'bg-[#E4F8ED]',
    // ... along with any other classes that are not currently functioning ...
  ],
  // ...
}
export default config

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

What could be causing this jQuery to malfunction?

Having trouble with the functionality of hasclass and this.addclass. if ($('.sidebar-menu-container li').hasClass('current-menu-item')) { $(this).addClass('expanded'); } Check out this CodePen for reference. ...

Integrating foundation-sites with webpack, unable to apply styles

Delving into the world of webpack for the first time has been quite a daunting experience! I'm attempting to set up the foundation for sites, but I feel completely lost when it comes to configuring it properly. Here is my Webpack configuration: var ...

Multiline text that appears inline

Is there a way to achieve this output in HTML or using CSS? This is the text: A very long piece of content that wraps automatically onto multiple lines Take note of how the text wraps and aligns on the left side. I am aware that tables can be used for t ...

Adjust the color palette size when the zoom level is modified in the responsive mode within Angular

I am currently working with Angular 15 and attempting to adjust the color palette size depending on the zoom level. <input #primaryColor (change)="colorChange($event,'primary')" formControlName="primaryColor" class="co ...

Chrome isn't showing the Background Image

I am currently working on coding a basic HTML/CSS page and I want to include a background-image within a div element that links to a URL. Interestingly, my code is functioning properly in Safari (Mac) and Firefox but unfortunately not showing the desired r ...

Incorporate zoom feature into the jQuery polaroid gallery

Currently, I am utilizing a jQuery and CSS3 photo gallery found on this website. My goal is to allow the images to enlarge when clicked, however, the method provided by the author isn't very clear to me, as I'm not an expert in jQuery. I attempt ...

The current layout of the div is hindering the ability to switch from vertical scrolling to horizontal scrolling

I'm currently utilizing this scroll converter tool to transform vertical scrolling into horizontal scrolling. However, despite correct script inclusion and initialization, the conversion is not working as expected. It seems like there might be an issu ...

Is there a way to transfer multiple functions using a single context?

Having created individual contexts for my functions, I now seek to optimize them by consolidating all functions into a single context provider. The three functions that handle cart options are: handleAddProduct handleRemoveProduct handleC ...

Error 504 occurred on AWS EC2 when attempting to access a specific external API URL

Here is a Next.js api route that I have set up for testing. All 4 axois calls work perfectly in localhost, but when deployed on AWS EC2 in production, the last 2 calls result in a 504 gateway time-out error. I have considered the possibility of issues wi ...

Space within a series of photographs

Looking for some assistance: I am trying to maintain a consistent margin of 10px between posts and between photos in a photoset. However, when a post is a photoset, the margins of the bottom photo and the overall post add up to 20px. I want to retain the ...

New example of how to use the "useSession" syntax in Next Auth

Currently, I am delving into the next-auth documentation and feeling perplexed by the syntax used in the useSession hook. The way it's showcased in the documentation is as follows: const { data: session, status } = useSession() My confusion stems f ...

Tips on choosing a child element with a parameter in React

Is it possible to pass a parameter in my function and use it to select a child of my JSON parse? I want to create a function (checkMatch) that can check if a username in my database matches with the input value. It should return 1 if there is a match, oth ...

The use of fs.writeFileSync is invalid and will not work for this operation

Encountering an issue while working with fs in next.js, receiving the following error message: TypeError: fs.writeFileSync is not a function Here's a snippet from my package.json: resolve: { fallback: { "fs": false }, } ...

My function handler is not being triggered when using React's onClientClick

I'm facing an issue with a button component I have, let's refer to it as < MyButton >. <MyButton onClick={this.props.calculate} onClientClick={this.changeColor} > Calculate </MyButton> Whenever I click the button, my cal ...

The npm build process encountered an unexpected token error in jsdom

Encountering an error with my next.js app when running "npm run build". The specific error message is as follows: > Build error occurred /var/www/directoryname/node_modules/jsdom/lib/jsdom/browser/parser/html.js:170 after._pushedOnStackOfOpenElement ...

What is the correct way to initialize a variable that will store the output of setInterval?

While examining a question, I came across someone's solution that proposed updating the code below. In the comments section, it was suggested: Instead of setting this.tm to undefined, we should set it to 0. Since it's a time interval, it shoul ...

Empty canvas when Material UI Modal transitions states

I've been struggling to make a simple modal using material UI, but every time I try to change the state, it just shows a blank white page. Can anyone help me figure out why this is happening? Here's the code snippet: import {Button,Modal} fro ...

Generating a new display div element using an anchor link

I've set up a div container with a button that, upon clicking, adds a class to an element in my markup causing it to expand and take over the entire screen. Markup before: <section class="isi" data-trigger="toggle" data-trigger-class="isi--show-i ...

Start the node server, send a curl request, and then shut down the server within the Dockerfile

My Dockerfile is quite simple: FROM node:16 COPY . . RUN npm install CMD ["npm", "run", "dev"] This Dockerfile runs a NextJS application. However, I am facing an issue where I need to make two CURL Requests from the container but using them in the CMD c ...

What is the best way to create a continuous typewriter effect in Next.js?

I have a unique project that features a typewriter effect, but I'm encountering an issue where it only types the text once. What I really want is for the typewriter effect to continuously loop, starting over and typing out the words again. I've b ...