Setting the color for the :hover and :active states on a react JSX component: A step-by-step guide

<button 
   onClick={fetchExchangeRates}
   style={{ backgroundColor: `${selectedColor}` }}
   className="hover text-white px-3 py-1 flex justify-center items-center gap-2 text- rounded-md"
   > Convert
   <FontAwesomeIcon className='text-white' icon={faArrowRight} />
</button>

In my Redux store, I have set up to fetch the color dynamically and apply it. Currently, I can only apply the main color but am unable to implement UX improvement features like button click and hover effects.

The challenge here is to achieve this dynamically.

Another problem I noticed is:

  const colorOptions = ["#C53030", "#2F855A", "#1E40AF", "#6B46C1", "#D97706", "#B83280",];
  const colors = [
    { hover: "#dc2626", main: "#b91c1c", active: "#991b1b" }, // red
    { hover: "#16a34a", main: "#15803d", active: "#166534" }, // green
    { hover: "#2563eb", main: "#1d4ed8", active: "#1e40af" }, // blue
    { hover: "#9333ea", main: "#7e22ce", active: "#6b21a8" }, // purple
    { hover: "#ea580c", main: "#c2410c", active: "#9a3412" }, // orange
    { hover: "#e11d48", main: "#be123c", active: "#9f1239" }, // rose
  ]
  return (
    <div className="grid grid-cols-3 gap-5 sm:gap-2 rounded-md bg-white p-5 sm:p-2 w-max mx-auto">
      {colors.map((color, index) => {
        const c = "blue";
        const backgroundColor = `bg-[blue]`; // works fine with string values
        // const backgroundColor = `bg-[blue]`; // Works fine as template literal
        // const backgroundColor = `bg-[${c}]`; // but doesn't work if we try to modify the string
        console.log(backgroundColor);
        return (
          <div
            key={index}
            // style={{ backgroundColor: color }}
             className={`h-12 w-12 sm:h-6 sm:w-6 rounded-full ${backgroundColor}`}
            onClick={() => handleColorChange(color)}
          ></div>
        );
      })}
    </div>

  )

I discovered that dynamically changing Tailwind CSS class values is not possible. Predefined values like bg-[#fff] work, but for other properties like text and borders, a more flexible approach is needed.

colors = [
   {backgroundHover: "bg-red-600", backgroundColor : "bg-red-700", backgroundAction : "bg-red-800", textColor : "text-red-700", borderColor : "border-red-700"},
{backgroundHover: "bg-green-600", backgroundColor : "bg-green-700", backgroundAction : "bg-green-800", textColor : "text-green-700", borderColor : "border-green-700"},
{backgroundHover: "bg-blue-600", backgroundColor : "bg-blue-700", backgroundAction : "bg-blue-800", textColor : "text-blue-700", borderColor : "border-blue-700"},
{backgroundHover: "bg-orange-600", backgroundColor : "bg-orange-700", backgroundAction : "bg-orange-800", textColor : "text-orange-700", borderColor : "border-orange-700"},
]

This hardcodes the implementation, making it less programmatic.

My expectations are:

  1. I want to dynamically change the hover and active colors of a button, in addition to setting text and border colors dynamically.
  2. While this is achievable through Tailwind CSS using a more manual approach, how can we accomplish this with normal CSS?

Answer №1

If you want to incorporate dynamic colors with Tailwind variants, one option is to set CSS variables on the element:

{colors.map((color, index) => {
  <div
    …
    style={{
      '--main': color.main,
      '--hover': color.hover,
      '--active': color.active,
    }}
    className="… bg-[--main] hover:bg-[--hover] active:bg-[--active]`}
  >

To expand this concept to text and border colors, you could do something like this:

text-[color:--main] border-[color:--main]

I have utilized the CSS variable shortcut syntax introduced in Tailwind v3.3. For versions of Tailwind prior to 3.3, you would need to include the var() function, such as bg-[var(--main)].

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

Inconsistent CSS3 transitions behavior in Firefox 4

I have been playing around with some css3 transitions and created a slider test. It works perfectly in webkit browsers, but I have noticed an issue in Firefox 4. When clicking on the left link for the first time, the slider is supposed to slide to the left ...

There was a parsing error due to encountering an unexpected reserved word 'interface' in the code, as flagged

I'm encountering an issue with my code when trying to utilize Props. The error message I'm receiving is "Parsing error: Unexpected reserved word 'interface'. (3:0)eslint". This project is being developed using next with TypeScript. Er ...

Cannot render <Image> inside <Section> component

As a beginner in React, I am attempting to create an app following a tutorial. In my component, I utilized the figure tag but it's not showing up when inspecting element in Chrome. Here are the code snippets: The tutorial includes a div tag as a chil ...

One possible revision: "Displaying errors on specific fields based on the results received from the API endpoint, without the use

When my API endpoint returns a 400 Bad Request with Validation Errors from FluentValidation, I aim to display these errors on the corresponding fields for user clarity. using Ardalis.ApiEndpoints; using MediatR; using Microsoft.AspNetCore.Mvc; using Que ...

Is there a method to view text options that are too long within a fixed width <select multiple> HTML box?

Here is the code I am working with: <div id='div2' style='height: 430px; width: 350px; overflow:auto;'> <select multiple id="id" size="28" style="FONT-SIZE: 12px; FONT-FAMILY: Arial; width: 100%"> It's a challenge bec ...

Time Unleashed: Moment.js (Relative time)

I am currently developing a social networking app using react.js. In order to display the relative time when a user adds a post, I am utilizing moment.js. However, I am facing an issue where even if the post was created two days ago, it only displays "a fe ...

Dealing with the error "TypeError: Unable to access the property 'useState' of null" in React Framework - Developing an NPM Package

My goal is to develop a local npm package that includes various React components under the name myscript-package. ./package.json { "name": "pack-script", "version": "0.1.0", "private": true, "d ...

Troubleshooting error in data structure for nested dynamic routes with Next.js getStaticPaths

I am working on a page called [categories][price].js and I am attempting to achieve a particular data structure within the getStaticPaths function. For example, I want to have paths like cat1/10, cat1/20, cat1/30, cat2/10, cat2/20, etc. I came across this ...

Creating dynamic elements in JavaScript and assigning them unique IDs

Hi there, I'm currently working on a project that requires generating dynamic divs with a textbox and delete button inside each one. The challenge I'm facing is figuring out how to assign a unique ID to each textbox element so that I can properly ...

Building a MERN-stack application with user authentication using react-router, all without the need

I am currently in the process of implementing authentication for my application, but I have a specific question. I have set up basic authentication on the backend, generating a token that is then sent to the frontend and stored in a cookie. I have learned ...

Align the Media center div within a column utilizing Bootstrap

I have a template in html with a media object containing a logo and text, both within a column of width 5. Currently, it is not centered and aligned to the left. I am looking for a way to centrally align the media block within the column, regardless of its ...

When the user signs in with Next-auth, they will be redirected to /signin with

After following the documentation to implement next-auth, I encountered an issue. When I visit http://localhost:3001/api/auth/signin, I see a page with a link (https://i.stack.imgur.com/xb0fx.png) but clicking "signin with Google or GitHub" just refreshes ...

The argument passed cannot be assigned to the parameter required

Currently, I am in the process of transitioning an existing React project from JavaScript to TypeScript. One function in particular that I am working on is shown below: const isSad = async (value: string) => { return await fetch(process.env.REACT_AP ...

What could be the reason for the malfunction of jQuery's show() function?

Using jQuery, I have implemented a functionality to hide a div using the hide() method. However, upon clicking a link, the div is supposed to show but unexpectedly disappears after appearing briefly. HTML Code Snippet <div id="introContent"> & ...

Setting up button value dynamically according to dropdown selection in Angular 2

I'm a beginner in angular 2 and I have a button with a dropdown. When I select an option from the dropdown, I want its value to be displayed on the button. The CSS code for styling the dropdown is provided below: .common_select_box { width: 100%; } ...

Tips for incorporating a svg file into your React project

I am facing an issue with my custom React, Typescript, and Webpack project. I am trying to import a basic .svg file and utilize it in one of my components. However, Typescript is throwing the following error: Cannot find module I have tried installing s ...

Troubleshooting problem with infinite scrolling in AngularJS with Ionic framework

I recently created a webpage with an infinite scroll page load more script using Ionic AngularJS. However, I encountered an issue where the page restarts from the beginning once it reaches the bottom. Below is the HTML code snippet: <ion-content class ...

Issue with nextElementSibling not applying CSS style

My current issue revolves around a button that is designed to open or close a collapsible div. The HTML structure of this element looks like the following: <div class='outer-collapsible'> <button type='button' class='col ...

Tips for utilizing Redux to send product IDs with a count in React Native for an ecommerce application, similar to the functionality of an

Creating a platform similar to eCommerce where I aim to include the functionality of adding items to cart and displaying the count on the icon. The count should also show the product based on the ID stored in an array. Here is my reducer code: cons ...

The Material-UI dialog is experiencing a flickering issue when incorporating Redux to manage the open

I am currently facing an issue with moving the open state of a material-ui dialog to redux in order to prevent it from closing during a rerender. However, I am encountering difficulties with the dialog's behavior when a rerender occurs. Even though th ...