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

Customizing the color of a select dropdown in Bootstrap using CSS styling

I am having difficulty changing the default blue color for Bootstrap select dropdowns. Despite trying :hover and :active selectors on both option and select, I have not been successful in making the desired changes. Could anyone provide insight regarding ...

Employing delegate for switching roles between classes

I'm having trouble using the jQuery delegate function to toggle classes. What I want to achieve is toggling the class of <li class="unselected-values"> to <li class="<li class="unselected-values"> when the client clicks on the label ...

Discover how to generate nested dynamic routes in NextJS by linking to MongoDB data using the getStaticProps and getStaticPaths functions

Currently, I am facing a challenge with implementing dynamic paths in NextJS and I'm struggling to find a solution. Let me provide some context for better understanding. I am working on developing an ecommerce application using NextJS, and the folder ...

Is animation not functioning for SVG path within a clip path on Firefox?

Creating the HTML for a unique effect: <svg class="svg-defs2" version="1.1" xmlns="http://www.w3.org/2000/svg" height="200" width="640"> <defs> <clipPath id="clipping2"> <!--Adjusting the x-coordinate of start will expand ...

The size of the website elements needs to be increased for better visibility on mobile devices

While developing the official website for my Discord bot - Idle Baker, I opted to utilize Bootstrap 5 for its user-friendly design features, making it easier than dealing with extensive CSS coding. After completing the homepage of the site, I encountered ...

While using the Android Firefox browser, I noticed that the keyboard is causing my screen to shrink in size

As I work on creating a cross-platform HTML page, I have encountered an issue with text fields on Android smartphones. When I attempt to type in a text box, the keyboard pops up and causes my HTML page to shrink within the viewport. I'm curious to kn ...

Animating the navbar with CSS transitions

Seeking advice on adding a transition effect to my navbar. Specifically, I'd like to have a colored background appear below each link when hovered over. For example, when hovering over "HOME," a yellow color should display, and it should disappear whe ...

Fluid design: prevent alteration in body width caused by vertical scrollbar

I have successfully implemented a liquid layout for my website by setting the body tag width to 100%. <html> <head> </head> <body> <div id="container"> some content </div> </body> body { mar ...

Particles.js fails to persist as I scroll down the HTML page

After creating a website page, I incorporated Particles.js for the background. However, when I scroll down, the particles seem to be confined to the initial corner of the screen and do not continue downward. Here are my current particle settings: #particl ...

When coding on Github pages, the behavior of code blocks can vary depending on whether

I am interested in obtaining the offline version, which can be seen here: On the other hand, the online version has a different appearance: If you want to view the incorrect version, click on this direct link to visit the blog. A notable issue is the da ...

The erratic nature of Tailwind actions

Currently, I am immersed in a Livewire project and attempting to implement some Tailwind theme configurations. However, the process does not appear to be coherent whatsoever. Here is an excerpt of my Tailwind configuration: theme: { extend: { f ...

Encountering difficulties initiating NextJS with Nginx

After creating a fresh project using Next JS, I successfully accessed it through the browser using an IP and port like "http://127.0.0.1:4321/". You can view the attached image here. However, when attempting to connect to the project via Nginx with an IP ...

The React Bootstrap modal refuses to fully close no matter how many times I click away or even on the close button

I am facing an issue with a modal in my React component. When I open the modal, it does not completely close when I try to click away or hit the close button. The backdrop disappears but the modal itself remains on the screen. (Screenshots attached for r ...

Tips for ensuring browsers maintain the aspect ratio specified by width and height HTML attributes when CSS is applied

I am seeking a method to reserve space in my layout for images before they are loaded by adding width and height properties to the img element. This approach functions as anticipated: img { display: block; border: 1px solid tomato; } <img src="" ...

Exploring the feature of On Demand Cache Revalidation in Next JS 13 with a remote ASP .NET Core backend

Seeking guidance on leveraging NextJS cache revalidation for a specific use case that seems unique. Currently, I am in the process of developing an online food ordering platform where numerous restaurants (currently 30) can publish their menus for customer ...

Website layout looking unique due to pixel width adaptation from standard width

I'm currently working on a website with full width design. On my computer, the website displays as full width, but on other computers it shows extra space on the sides. How can I ensure that this website is truly full width? .wrapper_boxed { wid ...

Incorporate a comma after the second or third digit to separate currency values in JavaScript

Is there a way to add commas to currency values at the 3rd or 2nd place depending on the value itself? The desired output format is: 1000 => 1000 10000 => 10,000 210000 => 2,10,000 2010000 => 20,10,000 12010000 => 1,20,10,000 I am currentl ...

Tips for personalizing and adjusting the color scheme of a menu in ant design

I am currently working on a website using reactJs and ant design. However, I have encountered an issue with changing the color of a menu item when it is selected or hovered over. Here's the current menu: Menu Image I would like to change the white col ...

How can you change a particular inline style using the Firefox browser?

I am looking for a solution to override an inline style on a specific webpage within the Firefox browser without access to the source code. Previously, I would manually modify the page source using Firefox development tools. Specifically, I encounter a we ...

When using Next.js, having 13 parallel routes within a nested routing structure can trigger infinite rendering loops during

A strange phenomenon occurs where a page route inside a parallel route keeps re-rendering infinitely in development mode. app directory structure: app ├── page-with-parallel │ ├── @parallelroute │ │ └── page-inside-parallel ...