I'm noticing that my Tailwind styles don't take effect until I redefine them. What could be causing

My Tailwind classes are giving me trouble.

I faced an issue when I created a new component in the directory and placed my Button component there.

Whenever I restart the project in terminal, the styles do not apply to my button unless I manually define them again. Here are the files tailwind.config.css, Button.js, and Navbar.js:

tailwind.config.css:

/** @type {import('tailwindcss').Config} */
module.exports = {
  content: [
    "./pages/**/*.{js,ts,jsx,tsx,mdx}",
    "./components/**/*.{js,ts,jsx,tsx,mdx}",
    "./app/**/*.{js,ts,jsx,tsx,mdx}",
  ],
  theme: {
    extend: {
      colors: {
        primary: '#FFD700',
        secondary: '#00CED1',
        accent: '#FF6347',
        success: '#32CD32'
      },
    },
  },
  plugins: [],
};

Button.js:

'use client'
import React, { useState, useEffect } from 'react'

const Button = ({ children, color }) => {

    const [colorPicker, setColorPicker] = useState('')
    const [colorWeight, setColorWeight] = useState(0)
    
    useEffect(() => {
        switch (color) {
        case 'primary':
            setColorPicker('amber')
            setColorWeight(300)
            break;
        case 'secondary':
            setColorPicker('teal')
            setColorWeight(500)
            break;
        case 'seccess':
            setColorPicker('lime')
            setColorWeight(600)
            break;
        case 'accent':
            setColorPicker('red')
            setColorWeight(500)
            break;
    }
    }, [color])
    

  return (
    <div>
        <button className={`bg-${color} px-4 py-1 rounded-xl hover:bg-${colorPicker}-${colorWeight} focus:bg-${colorPicker}-${colorWeight + 100} focus:ring-4 focus:ring-${colorPicker}-${colorWeight - 200} duration-200 text-white`}>
            {children}
        </button>
    </div>
  )
}

export default Button

Navbar.js

import Link from 'next/link';
import Button from './Button';

const Navbar = () => {
  return (
    <div>
      <div className='flex justify-between items-center'>
        <div>
          <div className='flex'>
            <img src="" alt="Logo" />
            <p>Croissant</p>
          </div>
        </div>

        <div>
          <ul className='flex gap-3 items-center'>
            <Link href='/'>
              <li>Home</li>
            </Link>
            <Link href='/about'>
              <li>About me</li>
            </Link>
            <Link href='/posts'>
              <li>Posts</li>
            </Link>
            <Link href='/login'>
              <li>
              <Button color='primary'>Login</Button>
              </li>
            </Link>
          </ul>
        </div>
      </div>
    </div>
  )
}

export default Navbar

Answer №1

According to the documentation:

The key point 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 choose to use string interpolation or assemble partial class names together, Tailwind will not be able to identify them and therefore will not generate the corresponding CSS:

Avoid dynamically constructing class names

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

In the provided example, the strings text-red-600 and text-green-600 are incomplete, so Tailwind will not create those classes. Ensure that all class names used are complete:

Always use full class names

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

You have two options:

  • Create a dictionary mapping color to Tailwind class names:
    const Button = ({ children, color }) => {
      let classes = '';
    
      switch (color) {
        case 'primary':
          classes = 'bg-primary hover:bg-amber-300 focus:bg-amber-400 focus:ring-amber-100';
          break;
        case 'secondary':
          classes = 'bg-secondary hover:bg-teal-500 focus:bg-teal-600 focus:ring-teal-300';
          break;
        case 'success':
          classes = 'bg-success hover:bg-lime-600 focus:bg-lime-700 focus:ring-lime-400';
          break;
        case 'accent':
          classes = 'bg-accent hover:bg-red-500 focus:bg-red-600 focus:ring-red-300'
          break;
      }
    
      return (
        <div>
          <button className={`px-4 py-1 rounded-xl focus:ring-4 duration-200 text-white ${classes}`}>
            {children}
          </button>
        </div>
      )
    }
    
    Refactored using an object dictionary:
    const CLASSES = {
      primary: 'bg-primary hover:bg-amber-300 focus:bg-amber-400 focus:ring-amber-100',
      secondary: 'bg-secondary hover:bg-teal-500 focus:bg-teal-600 focus:ring-teal-300',
      success: 'bg-success hover:bg-lime-600 focus:bg-lime-700 focus:ring-lime-400',
      accent: 'bg-accent hover:bg-red-500 focus:bg-red-600 focus:ring-red-300,
    };
    
    const Button = ({ children, color }) => {
      return (
        <div>
          <button className={`px-4 py-1 rounded-xl focus:ring-4 duration-200 text-white ${CLASSES[color]}`}>
            {children}
          </button>
        </div>
      )
    }
    
    
  • Include the classes in the safelist, especially if you have a limited set of known colors:
    module.exports = {
      safelist: [
        { pattern: /^bg-(primary|secondary|success|accent)$/ },
        {
          pattern: /^bg-(amber|teal|lime|red)-300$/,
          variants: ['hover'],
        },
        // …
      ],
      // …
    ];
    

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

Issue with popup display in React Big Calendar

I'm currently working on a calendar project using React-Big-Calendar, but I've run into an issue with the popup feature not functioning properly. <div className={styles.calendarContainer} style={{ height: "700px" }}> <C ...

NextJS: Issue: Accessing a client module from a server component is not allowed. The imported name must be passed through instead

My current NextJS setup is structured as shown below: app/page.js 'use client'; import React from 'react'; export default function Home() { return (<div>Testing</div>); } app/layout.js export const metadata = { title ...

Determining the top element displayed in a div: A guide

Looking for an answer on how to determine the top visible element while scrolling? You may find some insights in this post: (Check if element is visible after scrolling). My scenario is slightly different - I have a scrollable div containing multiple ele ...

Switch up the current Slick Carousel display by utilizing a div element

We have implemented the slick carousel to show only one slide at a time within the <div class='item__wrapper'>. Beneath this are three items, and we want the slick carousel to update when any of these items are clicked. Issues Using item ...

Create a next.config.js file to optimize a PWA application and include next/bundle-analyzer for performance analysis

I am currently working on my next.config.js file and I am looking to integrate next/bundle-analyzer /** @type {import('next').NextConfig} */ const withPWA = require("next-pwa")({ dest: "public", register: true, skipWait ...

When using jQuery to select elements of a specific class, make sure to exclude the element that triggered the

A dynamic number of divs are generated from a data source. Each div contains an image button and another div with text. While the actual scenario is more complex, we can present a simplified version: <div id="main"> <div id="content_block_1" ...

Animation Effects in Opera and Internet Explorer

Just unveiled my latest project, CSSload.net - an awesome tool for generating CSS spinners and bars. The animations are running smoothly on Firefox and Webkit browsers. Curious if anyone has tips on animating elements like this in Opera and IE? ...

Use CSS to insert a solid rectangle into the contents of a table cell

Struggling with the HTML code that defines a table? Here is an example: <table> <th> <td style="width:200px"> col1 </td> </th> <tr> <td id="a1"> text1 </td> </t ...

What could be causing my tabs (such as HOME, ABOUT ME..) not displaying the correct paragraph or section content?

I have set up navigation tabs on my website using anchor tags, but they are currently not linked to any specific paragraphs. I want the corresponding paragraph to be displayed when a tab is clicked, but I'm unsure how to add this functionality using j ...

The results of running 'npm run dev' and 'npm run build prod' are different from each other

Currently, I am in the process of developing a progressive web app using Vue.js. During development, I utilize the command npm run dev to initiate the local server that serves the files over at http://localhost:8080/. When it comes time to build for produ ...

The Bootstrap navbar-fixed-top is failing to function properly within the confines of my "content" div

My goal is to utilize the bootstrap navbar-fixed-top within my id="content" div. However, when I apply the navbar-fixed-top class like this: <nav class="navbar navbar-default navbar-fixed-top navbar-shadow"> The navbar ends up on top of everything ...

What could be causing my bounce animation to begin 50 pixels higher than its intended starting point?

Trying to create a bouncing effect on text Check out my attempt here. It seems like the bug is in this area. @keyframes bounce{ 0%, 40%{ transform:scale(2,.5) translate(0,100px); } 45%,55%{ transform:translate(0,-50px); } 55%, 100%{ ...

What could cause the cookie value in the dynamic route to differ?

After implementing a program with next js, I encountered an issue related to using cookies on dynamic pages. The problem is that the cookie value seems to be shared across different pages, when in fact each page should have its own unique cookie. My goal ...

The navigation icon on my website refuses to close

Hey there, I'm having some trouble creating a side navigation menu. The issue I am facing is that the menu opens without any problem, but then I can't seem to figure out how to close it using a second "onclick()" function. If you could take a lo ...

Complications arising from IE when using strict doctype with CSS and jQuery

Here's the code I'm using for a sliding caption effect on my gallery site: I specifically implemented the last effect which is the Caption Sliding (Partially Hidden to Visible). $('.boxgrid.caption').hover(function(){ $(".cover", th ...

My navigation bar is giving me a bit of trouble, as there are two separate issues that seem to be interconnected

Looking for some help with my navigation bar layout. You can also check out the code on fiddle http://jsfiddle.net/SgtRx/ (should have done this earlier, sorry). I'm a beginner when it comes to coding, so please bear with me if I make any mistakes. ...

Mastering the technique of showcasing landscape using CSS3

I'm working on an HTML and CSS3 report with multiple columns. I am trying to print it in landscape orientation using HTML and CSS3. I attempted rotating the body and table, but only half of the table is visible while the other half is cut off or hidde ...

Struggling to locate production files with the combination of `fast-glob` and `process.cwd()` when dealing with dynamic route segments

In the directory structure, I have a blog page located at app/[locale]/home/blog/page.tsx. import glob from 'fast-glob' import path from 'path' const BlogPage = async () => { let pages = await glob('**/*.mdx', { cwd: ...

Aligning Content in the Header

Currently, I am attempting to place a logo on my WordPress site right at the top of the header above the menus and in the center. Even though I've positioned it at the top, I'm struggling to align it horizontally in the center. I've experime ...

Issues with message display validation in jQuery

Validation has been applied to the form, and there are div elements within the input fields with corresponding IDs. The goal is to display error messages within those divs. Specifically, if an input field is missing, the errorMessage should be set in the ...