Guide on altering a Tailwind Class depending on the React State or Props

Currently, I am working on a Progress Bar Component and utilizing the following versions:

"next": "13.4.4",
"react": "18.2.0",
"react-dom": "18.2.0",
"classnames": "^2.3.2",

I am facing an issue where I am unable to change the width (Tailwind Class) of the Progress Thumb based on the currentValue Props. I have encountered this problem previously, but now I am seeking assistance. Additionally, I am using classNames() to improve class conditionals.

Below is my code snippet:


import classNames from 'classnames'
import React from 'react'

type ProgressBarProps = {
  maxValue?: number
  currentValue: number
  showNumbers?: boolean
  orientation?: 'vertical' | 'horizontal'
}

export const ProgressBar = ({
  currentValue,
  maxValue = 100,
  showNumbers = true,
  orientation = 'vertical',
}: ProgressBarProps) => { 

  return (
    <div
      className={classNames('flex items-center w-full gap-2', {
        'flex-row': orientation === 'horizontal',
        'flex-col': orientation === 'vertical',
      })}
    >

      // -> Progress Wrapper
      <div className="flex items-center w-full h-2 gap-2 rounded-md bg-third-250">

       // -> Progress Thumb
        <div
          className={classNames(`h-full bg-primary-500 `, {
            'rounded-md': maxValue === currentValue,
            'rounded-tl-md rounded-bl-md': maxValue !== currentValue,
            [`w-[${currentValue}%]`]: currentValue,
          })}
        />

      </div>

      // Irrelevant right now
      {renderNumericProgress()}

    </div>
  )
}

When inspecting the HTML result in the Chrome Console, we can observe the w-[10%] that I'm passing as props to this component:

<div class="flex items-center w-full h-2 gap-2 rounded-md bg-third-250">
 <div class="h-full bg-primary-500  rounded-tl-md rounded- 
  bl-md w-[10%]">
 </div>
</div>

I have attempted the following approaches without success:

  • className={`w-[${currentValue}%]`}
  • className={classNames(`w-[${currentValue}%]`)}
  • className={twMerge(`w-[${currentValue}%]`)}

Answer №1

According to the guidelines:

The key thing to note about how Tailwind extracts class names is that it will only detect classes that are present as complete unbroken strings in your source files.

If you try to interpolate strings or concatenate partial class names, Tailwind won't be able to find them and hence won't generate the corresponding CSS:

Avoid creating dynamic class names

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

In the example above, the classes text-red-600 and text-green-600 are not legitimate, so Tailwind won't generate them. Make sure to always use complete class names:

Stick to using full class names

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

You might want to consider utilizing the style attribute instead like:

<div
  className={classNames(`h-full bg-primary-500 `, {
    'rounded-md': maxValue === currentValue,
    'rounded-tl-md rounded-bl-md': maxValue !== currentValue,
  })}
  style={{ width: `${currentValue}%` }}
/>

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

Shifting HTML table in Javascript by toggling checkboxes

When I click the checkbox, the table elements are not displaying inline. I am simply hiding the class "box". Do I need to write a special format? By default, the elements are displayed inline but when I check the checkbox, they shift. The column 'Stat ...

Variations in default export behavior in Webpack when using Typescript versus Javascript

In my React application, I have a page that imports a component from another file. // Code snippet from IconPage.tsx import {AccountBalanceIcon} from './icons'; <AccountBalanceIcon /> // Code snippet from ./icons.ts export { default as A ...

What is the best way to assign a starting value to the array within the `<FieldArray/>` component?

While working with react-final form, I have been building a form that includes conditional fields that are displayed when a user clicks a checkbox. If the checkbox is checked, a component is rendered. The implementation is similar to the example provided ...

Tips for styling cells in a certain column of an ng-repeat table

I am currently facing an issue with a table I have created where the last column is overflowing off the page. Despite being just one line of text, it extends beyond the right edge of the page without being visible or scrollable. The table is built using th ...

Getting blocked by CORS when trying to link an AWS React application to a Node.js API hosted on AWS

Seeking assistance with resolving CORS (Cross-Origin Resource Sharing) errors in my web application. Here are the crucial details of my setup: Front-End: React version 16.14. Back-End: Node.js version 16.19 with Express.js version 4.18.1. Server Instance: ...

What steps can I take to maintain the width while implementing jQuery's slideUp function?

I am facing a scenario where: http://www.jsfiddle.net/kPBbb/ After adding content to .content, the .wrapper shrinks itself, possibly due to the fact that the .content is set to display: none. I want the .wrapper to maintain its original size even after t ...

Tips for passing parameters to a function in stateless React components!

I'm working with a component that looks something like this (a simplified version): const MyComponent = () => { const handleClick = param => { console.log(param); } return ( <Link to={'/'} onClick={handleClick} v ...

Set the GridToolbarQuickFilter text box to have an outlined style in Material UI v5

How can I customize the appearance of the GridToolbarQuickFilter textbox, such as outlining it? Ideally, I would like to accomplish this through theme.tsx, but I am open to any suggestions. https://i.stack.imgur.com/H1Ojj.png I have experimented with var ...

Is it possible to alter the state of one page by clicking a link on another page?

Is it possible to update the state of a different page when a link is clicked and the user navigates to that page? For example: Homepage <Link href="/about"> <button>Click here for the About page</button> </Link> If a ...

Is there a way to turn off the pinch-to-zoom trackpad gesture or disable the Ctrl+wheel zoom function on a webpage

Take a look at this example - While zooming in on the image by pressing ctrl + scroll, the image zooms but the page itself does not scale. Only the image is affected by the zoom. I am attempting to replicate this functionality on my Next.js page. I have ...

Increase the Z-Index of the Header above the Material UI Modal Background

Currently, I'm in the process of developing a mobile version of a web application using Material UI. However, I am encountering some challenges when it comes to matching the designs accurately. My approach involves utilizing the MUI App-Bar in conjunc ...

Tips on getting your card to stay at the top

Screenshot of webpage HTML (EJS): In the HTML file, look for the section after <%- include("navbar.ejs") -%> inside the body tag. The ".cardholder" contains "anime-card" templates (card.ejs). The first and last div within ".cardholder" are ...

Can we utilize object properties in this manner?

Hey there! I've been experimenting with the react-bootstrap library recently, trying to get better at using it. While going through the tutorial, I came across some ES6 code that caught my attention. function FieldGroup({ id, label, help, ...props } ...

Error encounter when loading the chunk for FusionCharts's overlappedbar2d.js in React.js: fusioncharts.overlapped

Currently, I am working on a web application that utilizes next.js and FusionCharts. Within the app, various FusionChart types have already been set up. My task now is to integrate the Overlapping Bars chart as outlined in the following documentation: How ...

"The boundary of suspense was updated before completing hydration." This error occurs when utilizing suspense and dynamic import within Next.js

I am currently working on lazy loading a list of data using suspense and dynamic import in Nextjs. However, I encountered the following error: Error: This Suspense boundary received an update before it finished hydrating. This caused the boundary to switch ...

Images refusing to display within the div

I am attempting to insert an image onto my website, however, I am encountering issues with the code I have written: div#planet { z-index: -10; width: 450px; height: 549px; position: absolute; background: url("https://example.com/im ...

Footer button overrides list components due to improper implementation of vertical ion-scroll

Having some trouble setting up ion-scroll on a specific screen in my mobile application built with Ionic. On the Book page of my app, I'm encountering two main issues: https://i.stack.imgur.com/MnheG.png 1) The placement of the Confirm button doesn& ...

Managing repeated selections in a dropdown menu - MUI Select

Currently, in my implementation using MUI v5, I am faced with a scenario where I have two options with the same name. The issue arises when both of these options are selected simultaneously using the Select component. I am looking for guidance on how to r ...

A sleek CSS text link for a stylish video carousel

I am attempting to create a CSS-only text link to video slider within our Umbraco CMS. Due to the limitations of TinyMCE WYSIWYG, I am restricted in the amount of code I can use as it will strip out most of it. So far, I have developed a basic CSS slider ...

Connecting the material-ui dropdown to a table

Is there a way to connect a react material-ui dropdown to a table? I am working on a project where I have a drop-down list containing countries and a table displaying country names and their corresponding capital cities. The goal is to update the table b ...