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

putting a division element above a image carousel

Is there a way to overlay a div tag on top of a slideshow, similar to the one shown in this link? In the example provided, a div with the title "DISCOVER THE JOY OF COOKING" is positioned over a slideshow. Any tips on how I can achieve this effect? ...

using JQuery, add a class on click event or on page load

Solved It! After encountering a problem created by some sloppy moves on my part, I managed to solve it. However, another issue arose: adding the class current to li with data-tab="tab-1 upon page load. $('ul.tabs li').click(function(){ ...

`Problem with CSS in Firefox, functions properly in Chrome`

Can someone please check to see if they can find what I'm overlooking? It's working perfectly in Chrome 10 but not in Firefox 4. The aim is for it to look like an iPhone keyboard. http://jsfiddle.net/pfqdr/ UPDATE: http://jsfiddle.net/pfqdr/6/ ...

React Axios: When State Fails to Pass onClick Event

I have been working on a code where different buttons display their values when clicked. For example, button 1 will display its value when clicked (id=1), button 2 will display the value of button "2", and so on. The code is working perfectly fine. co ...

There appears to be an empty void on the website

If you could kindly click on this link & use CTRL + F to search for the text "Info", you will see a visual representation similar to the image below. There seems to be quite a bit of empty space below these texts. I experimented with padding, display: ...

The error message "bound Template cannot be used as component" is triggered when a storybook attempts to utilize children as an argument

As per the Storybook documentation, you can find more information at: // List.stories.ts | List.stories.tsx import React from 'react'; import { List, ListProps } from './List'; // ...

Enhancing the accessibility of Material UI Autocomplete through a Custom ListboxComponent

I have developed a custom ListboxComponent for the MUI Autocomplete component in MUI v4. How can I ensure that it meets the necessary accessibility requirements, such as navigating through options using the arrow keys? <Autocomplete ListboxComponent ...

Function for testing global variable stub in JavaScript

Currently, I am in the process of writing Unit tests for a React application. Within the page header, the tracking library 'mixpanel' is inserted between <script> tags as outlined in their documentation: . The documentation states that "Th ...

Information about Doughnut chart in React using the react-chartjs-2 package

Is there a way to write text directly on a Doughnut using react-chartjs-2? Most answers I came across explain how to place text in the center of a Doughnut, but not actually on it. Here is an image for reference: ...

Tips for optimizing HTML5 markup elements to render effectively in Internet Explorer

How can I ensure that HTML5 markup elements such as <header>, <section>, and <footer> are displayed properly in Internet Explorer? I've noticed that when I apply CSS to these elements, the styling doesn't always work as expecte ...

Step-by-step guide for serving static JavaScript files using NextJS

I am currently exploring the process of hosting static js and css files using NextJS. My journey began with creating a react app through create-react-app, where I developed an App component before executing the npm run build command. This resulted in the ...

"Effortless CSS Formatting in VS Code - A Guide to Automatic Styling

Recently started using VS code and I'm on the lookout for a solution to automatically format CSS whenever I save my work. Strangely, my searches haven't led me to any reliable extensions or clear guides on how to achieve auto formatting in VS cod ...

How to perfectly align a modal (Div) in Next.js using tailwindcss

I am in the process of setting up a blog using next.js, and for managing new or existing blog posts and their content, I have incorporated a modal. However, I am facing some challenges with tailwindcss as I'm unable to center the modal properly on the ...

Unable to get callback to function properly within request npm

I am facing some challenges with the callback function while using Request npm in my project. The API for users is built with Sailsjs, and I am using Reactjs for the front-end along with Request npm for communication with the API. There seem to be issues w ...

Unlocking new possibilities with Next Auth B2C in React and Next.js

On my journey to implement B2C login with React using Next and the Next Auth library, I encountered an issue when deploying the application. While everything works smoothly in localhost, a strange occurrence unfolds upon deployment. The cookie next-auth. ...

reconfigure form credentials with JavaScript

I am currently working on a form that includes a textbox and a button for submitting data using ajax. <input type="password" id="password" /> <button id="addaccount" onclick="showload();">Add</button> When the user clicks on the button, ...

React : utilize onItemTouchTap to alter the background color

Looking for some help with utilizing MenuItem from Material UI. Here is the code snippet I am working with: <Paper style={style.paper}> <Menu onItemTouchTap={onItemTouchTapCb}> <MenuItem primaryText="Quick Access" leftIcon= ...

Creating Styles in Material-UI using makeStyles: Tips for Styling by Element Name

I am currently facing a challenge of adding a rule for all <p> tags within the current component. Despite searching through various sources such as material-ui documentation and Stack Overflow, I have been unable to find any information on how to add ...

Retrieve the id for the chosen user name within a function that contains an array of objects

const userList = [ {name:"jonh" ,id:EAD1234}, {name:"peter" ,id:EAD1235}, {name:"matt" ,id:EAD1236}, {name:"henry" ,id:EAD1237}, ] In the array above, there are various users with their respective IDs. The goal is t ...

What is causing the content to overflow outside of the navbar on smaller screens or mobile devices?

/* *{ font-family: sans-serif; box-sizing: border-box; margin: 0; padding: 0; overflow-x: hidden; } */ .main { min-height: calc(100vh - 10rem); display: grid; place-items: center; } p { font-size: 4rem; line-height: 1.6; } nav ...