Troubleshooting the Hover Effect of Buttons in Next.js when Using Tailwind CSS for Dynamic Color Changes

Encountering a problem with button hover functionality in a Next.js component using Tailwind CSS. The objective is to alter the button's background color dynamically on hover based on a color value stored in the component's state.

This code functions flawlessly in a React.js application, but fails to trigger the hover effect in Next.js.

"use client";
import React, { useState } from "react";

const BottomButtons = ({ onHeaderTextChange }) => {
  const [selectedButton, setSelectedButton] = useState("Delivery Rate");

  const handleButtonClick = (buttonText) => {
    setSelectedButton(buttonText);
    onHeaderTextChange(buttonText);
  };

  const buttons = [
    { text: "Delivery Rate", color: "#00E096" },
    { text: "Click Rate", color: "#0E9AFF" },
    { text: "Open Rate", color: "#BF83FF" },
    { text: "Bounce Rate", color: "#FF947A" },
    { text: "Issues", color: "#FA5A7D" },
  ];

  return (
    <div className="flex items-center justify-end mb-4">
      {buttons.map((button, index) => (
        <button
          key={index}
          className={`p-2 hover:bg-[${button.color}] border`}
          onClick={() => handleButtonClick(button.text)}
        >
          {button.text}
        </button>
      ))}
    </div>
  );
};

export default BottomButtons;

Approaches Taken:

  • Ensured correctness of the button.color values matching Tailwind color names.
  • Examined for any conflicting styles through browser developer tools.
  • Confirmed proper configuration of Tailwind and purging of unused CSS.
  • Expected Outcome:
  • Anticipating the button's background color to adjust dynamically depending on the corresponding Tailwind color name within the hover:bg-[button.color] class upon hovering over the button element.

Further Details:

  • Verified that the code produces desired results in a pure React.js setting.
  • Suspecting that the issue may be tied to Next.js' server-side rendering (SSR) mechanism.

Answer №1

According to the information provided by TailwindCSS

Understanding Dynamic Class Names

An important principle of Tailwind is that it can only recognize classes that are complete and unbroken strings within your source code.

If you try to use string interpolation or combine partial class names, Tailwind will not be able to detect them and consequently will not generate the required CSS:

Therefore, as mentioned in the documentation, dynamically generating classes in the way depicted may not function correctly.

There are various solutions to address this issue, one of which suggests utilizing colorVariants as noted in the docs:

function BottomButtons() {

  const buttons = [
    { text: "Delivery Rate", color: "red" },
    { text: "Click Rate", color: "blue" },
    // remaining ....
  ]

  const colorVariants = {
    blue: 'hover:bg-[#00E096]',
    red: 'hover:bg-[#0E9AFF]',
  }

  return (
    <div className="flex items-center justify-end mb-4">
      {buttons.map((button, index) => (
        <button
          key={button.text}
          className={`p-2 ${button.color} border`}
        >
          {button.text}
        </button>
      ))}
    </div>
  )
}

However, for simplicity's sake, you could opt to skip the intermediate step with colorVariants and directly define the colors within the buttons array like so:

const buttons = [
  { text: "Delivery Rate", color: "hover:bg-[#00E096]" },
  { text: "Click Rate", color: "hover:bg-[#0E9AFF]" },
  { text: "Open Rate", color: "hover:bg-[#BF83FF]" },
  { text: "Bounce Rate", color: "hover:bg-[#FF947A]" },
  { text: "Issues", color: "hover:bg-[#FA5A7D]" },
];

<button
key={button.text}
className={`p-2 ${button.color} border`}>
 {button.text}
</button>

I have created a simple demonstration on Stackblitz

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

JavaScript: Specialized gravity diagram

To better understand the issue I am experiencing, please take a look at the image linked below: The concept and problem I am facing is related to creating a weight chart similar to the one shown in the picture or on this site , here is the description of ...

How does a state management library benefit a server-side rendered application?

I am currently utilizing NextJS as the library to serve a SSR application. While exploring the documentation and examples, I have come across numerous references to incorporating a state management library into the setup. Traditionally, I have used a sta ...

Determine if the same origin policy is in effect

Is there a method to determine if the same origin policy is applicable to a URL before attempting to use ajax methods? Below is an example of what I currently have: function testSameOrigin(url) { var loc = window.location, a = document.create ...

Don't allow users to switch views without saving their changes

We are working with a Backbone.js application that presents various forms to users. Our goal is simple: if a user navigates away from the page without saving the completed form, we need to show a confirmation dialog. When dealing with traditional forms, i ...

New button attribute incorporated in AJAX response automatically

data-original-text is automatically added in ajax success. Here is my code before: <button type="submit" disabled class="btn btn-primary btn-lg btn-block loader" id="idBtn">Verify</button> $(document).on("sub ...

Fontawesome is unable to update the class due to the presence of invalid characters in the string

const toggleDarkOrLight = document.getElementsByTagName('i')[0]; var toggled = false; const toggleFunction = () => { if (toggled === false) { toggleDarkOrLight.classList.remove('fa fa-toggle-off'); toggleDarkOrLight.classLi ...

What is the best way to send an object array from an express function to be displayed on the frontend?

//search.js file import axios from "axios"; export function storeInput(input, callback) { //input = document.getElementById("a").value; let result = []; console.log(input); if (!callback) return; axios.post("ht ...

Angular7 & Electron: Resolving the Issue of Loading Local Resources

I am encountering difficulties while working with electron. Although I can successfully load my project using ng serve, I encounter an error when attempting to open it with electron as shown in the developer tools Not allowed to load local resource: fil ...

What is causing class-validator decorators to delete properties when combined with class-transformer?

I am exploring the use of class-validator and class-transformer for validating API requests in a Next.js API route. Below is a simple API handler setup to showcase this: import { plainToInstance } from 'class-transformer'; import { IsString } fr ...

How do I retrieve the return value of another function in React?

I am working on a function called HandleCitiesArray where I need to access the myCitiesArray. To achieve this, I want to utilize the useSelector hook from Redux. Specifically, I aim to remove an object from initialState.myCities array. How can I go about ...

Building a custom CellRenderer in AGGrid using TypeScript within a React environment

Currently, I am utilizing React along with TypeScript and attempting to create a custom CellRenderer in AGGrid. My code is structured like this: PriorityCellRenderer.tsx import React from 'react'; function PriorityCellRenderer(props:any) { co ...

Unlock the potential of Power BI with this step-by-step guide on enhancing the Circle Card visual by incorporating unique formatting

Power BI Tutorial: Adding Formatting Options to the Circle Card Visual After completing step 8, I copied the code into my VS Code and encountered 2 error messages: Error message: "import VisualSettings - Module '"./settings"' has no e ...

Using React Native with TypeScript to Select the Parent and Child Checkboxes within a FlatList

My objective is to ensure that when a user selects a checkbox for one of the parent items ('Non Veg Biryanis', 'Pizzas', 'Drinks', 'Desserts') in the flatlist, all corresponding child items should also be selected au ...

Is it possible to customize the deep elements of ExpansionPanelSummary using styled-components in React?

After digging into the documentation and examples on how to customize Material UI styling with styled-components, I successfully applied styling to the root and "deeper elements" within an ExpansionPanel and ExpansionPanelDetails. However, when attempting ...

Retrieving data from MongoDB and presenting it neatly in Bootstrap cards

I have successfully retrieved data from MongoDB and displayed it in Bootstrap 5 cards. However, I am facing an issue where all the cards are appearing in a single row if there are multiple entries in the database. What I want to achieve is to utilize the ...

Keep an eye on the output of Firebase database in Angular 2

Just starting out in angular, so please be patient :) Using Angular 2 (version 1.0.4), Angular CLI, and NodeJs 7.9. I've been trying to create a centralized service that checks if a user is logged in, retrieves their data, and sends it back for the ...

Generate a dynamic key object in Angular/TypeScript

I am working with an object called "config" and an id named "id". My goal is to create an array of objects structured like this: [ "id" : { "config1: ... "config2: ... "config3: ... } "id2" : { "config ...

Trouble with Jsonp when using the getJSON function in jQuery

$(document).ready(function() { $.getJSON("http://quanta.net16.net/wordpressnew/test.php?jsoncallback=?", function(data) { alert('swag'); }); }); This is the JSON request I'm making and my data is properly contained within ?({object} ...

Is it possible to incorporate a next.js image onto the background design?

I've encountered an issue while attempting to create a fixed background image with a parallax effect using Tailwind CSS and Next.js Image. If you need to see an example of this in action, check out this Template Monster theme. Here's the code s ...

When implementing variables from input boxes, my SQL query fails to populate any data in the database table

I have been using phpMyAdmin to store test data. As I try to insert data from a form, I encounter an issue where no data gets inserted when using variables in the SQL query. Being new to coding, I am struggling to find a solution to this problem. Additiona ...