Issue encountered with Tailwind Color Classes not functioning correctly when triggered by a button click within NextJS and React Vite framework

Recently, I've developed a component showcasing the "Text Gradient" effect in Tailwind + React. The component comprises of 4 select dropdowns and a "randomize" button. Upon clicking the button or selecting an option from the dropdowns, the changes are supposed to be previewed.

However, for the first time ever, I'm facing an issue where the color classes are not being correctly applied. Even though they appear in the className attribute of the <h2> tag, the classes are rarely reflected on the screen. Furthermore, the colors that fail to apply also do not show up in Dev Tools -> Style Sidebar.

To provide more insight, I have created a 2-minute video demonstrating the problem:

Upon watching the video, you'll notice my attempts to generate results consistently, but most of the time, the text ends up becoming transparent with no color applied.

You might think that the issue lies within faulty classes. However, if I copy the classes and test them on play.tailwindcss.com, they work perfectly fine.

<h2 class="bg-gradient-to-r from-pink-700 via-yellow-800 to-lime-500 bg-clip-text text-center text-7xl font-bold text-transparent">Whats Up</h2>

Here's an example of a class that fails to work in my PreviewText.jsx file but functions flawlessly on play.tailwindcss.com, thereby confirming that there is nothing wrong with the Tailwind classes.

Below is the relevant code snippet:

Gradient useState Variable:

 const [gradient, setGradient] = useState({
direction: "bg-gradient-to-tl",
fromColor: "from-slate-800",
viaColor: "via-violet-500",
toColor: "to-zinc-400",
});

RandomizeGradient Function:

const randomizeTextGradient = () => {
    const randomDirection =
      gradientDirections[Math.floor(Math.random() * gradientDirections.length)]
        .value;
    const randomFromColor =
      fromArray[Math.floor(Math.random() * fromArray.length)].value;
    const randomViaColor =
      viaArray[Math.floor(Math.random() * viaArray.length)].value;
    const randomToColor =
      toArray[Math.floor(Math.random() * toArray.length)].value;

    const newGradient = {
      direction: randomDirection,
      fromColor: randomFromColor,
      viaColor: randomViaColor,
      toColor: randomToColor,
    };

    setGradient(newGradient);
};

TextGradient.tsx File:

 <section className="text-white bg-transparent border-t border-b border-zinc-800 my-6">
    <div className="py-4 mx-auto flex items-center gap-4 justify-between">
      <div className="flex gap-2">
        <button
          className="focus:outline-none p-2 bg-zinc-900 border rounded-md border-zinc-700 hover:bg-zinc-700"
          onClick={randomizeTextGradient}
        >
          <svg
            xmlns="http://www.w3.org/2000/svg"
            className="w-5 h-5 text-white"
            fill="#fff"
            viewBox="0 0 256 256"
          >
            ...
          </svg>
        </button>
        <CopyToClipboard
          ...
        </CopyToClipboard>
      </div>
      ...
    </div>
  </section>
  <div>
        <PreviewText gradient={gradient} />
  </div>

For those interested, here's how the classes are generated in the code:

    const colors = [
    "slate", "gray", "zinc", "neutral", "stone", "red",
    "orange", "amber", "yellow", "lime", "green", "emerald",
    "teal", "cyan", "sky", "blue", "indigo", "violet",
    "purple", "fuchsia", "pink", "rose",
  ];

  const numbers = [100, 200, 300, 400, 500, 600, 700, 800, 900];

  let fromArray = [];
  let viaArray = [];
  let toArray = [];

  colors.forEach((color) => {
    numbers.forEach((number) => {
      let fromValueLabel = `from-${color}-${number}`;
      let viaValueLabel = `via-${color}-${number}`;
      let ...

I've been troubleshooting this issue for 2 days without success. Any assistance you can offer would be greatly appreciated. I've tested this code in both NextJS and React Vite projects.

Answer №1

According to @Danila's point, it seems like there is a deviation from the recommended practice of dynamic class name usage in the documentation. The key takeaway is:

Avoid generating class names dynamically

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

In the given example, the classes text-red-600 and text-green-600 are not predefined in Tailwind CSS, therefore, they will not be created by Tailwind.

Instead, ensure that all class names you apply already exist in the stylesheet:

Always utilize complete class names

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

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

"Exclusive Mui sx styles will be applied only when a specific breakpoint

As I update my old mui styling to utilize the sx attribute, I've noticed the ability to specify styles for different breakpoints using sx = {{ someCssProp: { xs: ..., md: ... and so on. Prior to this, I had been using theme.breakpoints.only for some ...

How can I add navigation dots to my slider?

I've been experimenting with my slider and I managed to make it slide automatically. However, the issue is that there is no option to manually navigate through the slides. I am looking to add navigation dots at the bottom so users can easily switch be ...

JQuery is unable to access a specific property within a JSON object

Ive built a React component that fetches JSON data from the backend and displays it in a tabular layout. var App = React.createClass({ loadMoviesFromServer: function () { var self = this; $.ajax({ url: "http://localhost:9000/movies" } ...

What could be causing the background to disappear when the window width is reduced?

Can someone please explain why, after reducing the width of the window on , there is no wooden background in the upper right corner? Thank you in advance. ...

Text hidden within the image, each line concealing a separate message

I am having an issue where my image is overlaying the text. I would like the text to wrap around the image and for any hidden text to appear on a different line. How can this be achieved? Here is the CSS code I am using: div.relative { position: relati ...

Ensuring CSS tables fill their parent container or overflow as necessary

How can I create a dynamic table with variable-sized columns that always fills the parent area, regardless of the number of cells? The goal is to allow scrolling if needed, but ensure the table spans the entire parent space even with few cells. I've ...

Attempting to create a sidebar using redux in React

As a newcomer to react, I am currently working on creating a sidebar. So far, I have managed to access the reducer successfully. // sidebarReducer.js const sidebar = (state = { visible: false }, action) => { switch (action.type) { case "SHOW": ...

Creating dynamic routes with Map in ReactJS: a beginner's guide

In the sample code below, I have added a column to the children property that includes my component. I am attempting to pass this to my Route element using map in order to dynamically populate the React Route. navLink.js export const navLinks = [ { ...

Steps to enable navigation to external pages from a ReactJS app

I am working on a simple ReactJS application: [Demo] [Source] I am trying to implement navigation within the app from external sources without refreshing the web page. This functionality should be similar to using this.props.history.push(...). /public/i ...

The error message "Shadcn - Type 'CheckedState' cannot be assigned to type 'boolean | ChangeEvent<Element>'" appeared in the console

I've run into an issue with my code that utilizes the shadcdn library. The problem arises specifically with the Checkbox onCheckedChange event in this snippet: <FormField control={form.control} name="remember" render={({field} ...

What is the best way to automatically assign a class attribute to all form widgets in Django?

Whenever I create a form using Django, I want the input tag to automatically include a specific CSS class (form-control). Currently, I have to manually add lines of code in my forms.py file for each field like this: class InsertItem(forms.ModelForm): ...

Using the pages folder in NextJS may lead to static exports being blocked due to the utilization of useContext

I am encountering an issue with a Next.JS project where it functions properly with 'npm run dev', but encounters a problem when exporting. In this simplified example, I have removed almost everything from componentA except the useContext stateme ...

Centering the header image on the screen creates a visually appealing focal point

Looking to design a header image for my website that always stays centered. I want the image to stand out and remain in the middle even when the browser window is resized. I found an example on this website that achieves this effortlessly. ...

Can you use dipatsch instead of useSelector in your code?

Programming Language : JavaScript with React and Redux Situation: I have a component that displays a list of quotes based on user filters and category selections. Within my filter component, I store the selected value (buttonsData) and dynamically render ...

Determining the combined value of table columns with the help of React hooks and Material UI

Is there a way to calculate and display the average value of columns at the bottom of a table? The rows look like this: const rows = [ createData("Frozen yoghurt", 159, 6.0, 24, 4.0), createData("Ice cream sandwich", 237, 9.0, 37, 4.3), createData( ...

Stopping a div from causing the parent table's width to increase

I've encountered an interesting challenge with a project I'm working on. I need to inject markup into pages that I don't have control over, specifically within tables. The issue arises when my injected div causes the parent table to expand u ...

Possible rewrite: "Tips for extracting columns and rows from object data in React using '@material-ui/data-grid'"

I am currently working on retrieving data from a mockapi and displaying it on my data grid. The data grid requires specific rows and columns to be defined. While I have manually set these up for practice, I now aim to fetch object data using axios and th ...

Generate a container element that occupies the remaining space on the screen under a header of adjustable height

I'm trying to create a layout where the header height can vary, but the footer has a fixed height. I want the left nav and content sections to fill the screen height, with the left nav having a fixed width and the content taking up the remainder. Is ...

Clue model cannot be overwritten once compiled due to an OverwriteModelError in Mongoose for NextJS

Currently, I am in the process of developing a straightforward web application using NextJS and am aiming to integrate Mongoose for handling my database operations. The error that is plaguing me can be seen at this link: https://i.stack.imgur.com/OA1JD.pn ...

Setting up a serverless next.js react application on AWS Lambda resulted in receiving the message: {"error": "Server encountered an internal problem"}

Recently, I attempted to deploy a serverless React.js Next application on AWS Lambda. Despite successful deployment in Node.js and receiving an AWS CloudFormation status of UPDATE_COMPLETE, I encountered an issue when trying to access the endpoint link. A ...