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

Running your Next.js urql authentication exchange on the server instead of the client

Encountering an issue when attempting to integrate an auth exchange into my urql client. It runs on the server during app startup and then on the client until a page refresh. The problem lies within my getAuth function, shown below: const getAuth = async ( ...

jQuery and CSS animation implemented on website performs flawlessly on all browsers, with the exception

I have recently started learning jQuery and I am facing an issue with the website linked below. It works perfectly in Firefox, Chrome, and Opera but not in Safari. <head> <meta charset="UTF-8"> <meta name="viewport" content="width=devic ...

Unusual glitch with paint/rendering in Safari while navigating through a lengthy list of content

Encountering a peculiar problem where a page displaying a grid of boxes is experiencing issues in Safari, Chrome on iPhone 11 Pro, iPhone 13 Pro, and Chrome on Pixel 4a. Other devices are not affected. Symptoms include unresponsiveness and blank sections a ...

Tips for properly modifying an attribute within an array of objects in JavaScript using ReactJS

My array of objects looks like this: this.state = { itemSquare: [{ item: "bomb", status: false }, { item: "bomb", status: false }, { item: "bomb", status: false }, { item: "bomb", status: ...

Establish a new data entry and link it to an already existing entry using the Prisma client (forming a one-to-one relationship)

I am currently developing a Next JS application utilizing prisma and postgresql. The database consists of 2 main tables: User and Profile Here is the schema structure for both tables: model User { id String @id @default(cuid()) name ...

Preview multiple images while uploading in a React JS application

In order to achieve multiple image upload with preview using React JS, I attempted the code below. However, I encountered an error in the console: Uncaught DOMException: Failed to set the 'value' property on 'HTMLInputElement': This ...

CSS3PIE is failing to function properly in Internet Explorer

Looking for a solution to achieve rounded corners in Internet Explorer? Consider using . In my CSS file named template.css, I have included the following code which is loaded when the page loads on Joomla 1.5. .form_field {color:#222 !important; border:2p ...

Getting the Slider value using useRef: A step-by-step guide

Is it possible to prevent the re-rendering of the Slider component every time the slider changes by using useRef instead of useState? How can I access the value of the slider with useRef? When logging ref.current, I see a nested structure of spans without ...

I'm encountering difficulties with customizing the root styling of material-ui's DialogActions

Check out the two buttons in a DialogActions just like this. This is the JSX snippet I'm working with: <DialogActions classes={{ root: classes.dialogActionsLeft }}> <Button autoFocus onClick={() => { setOpen(false); }} ...

Can an icon be included in Material UI's DataGrid headers when the sorting direction is not defined?

In the DataGrid's API of Material UI, you can see how to include a sort icon for ascending and descending directions. By default, these icons are shown as arrow up and arrow down symbols but can be customized using props. However, my project requires ...

Issues with data not flowing through in Rebase/Redux/Firebase integration with React

Currently attempting to synchronize a table of data from Firebase 3.x.x with my React application. This library seems to be the most popular choice for this task. See below for the code with placeholders filled in. App.js: componentDidMount() { var bas ...

Centralize Arabic symbol characters

Is it possible to center the symbols that by default go above characters such as مُحَمَّد? .wrapper { text-align: center; vertical-align: center; } span { font-size: 4rem; display: inline-block; padding: 2rem; margin: 0.2rem; ba ...

Is it feasible to implement the Bootstrap GRID System?

Hello there! I am currently exploring a potential scenario. When viewing on a desktop or laptop, the layout should look like this: <div class="col-md-3"> sidebar </div> <div class="col-md-9"> article </div> On a smaller screen, ...

Saving User Input into a Google Sheet with React.js

I'm having trouble uploading all of my form data to Google Sheet. I've tried using the Gsheet API call below, but it only updates one cell due to dimension issues. { "requests": [ { "repeatCell": { "range": { "start ...

Guidelines for Implementing Stylesheets from a Referenced Node Module

I am currently developing a VS Code module that incorporates highlight.js to produce HTML for syntax highlighting of source code. Within the highlight.js npm package, there is a directory named styles containing various CSS files that I intend to utilize. ...

Can flexbox elements be animated as they scroll?

Wondering if it's feasible to animate flex elements upwards when scrolled? Attempting to replicate this effect: https://codepen.io/Sergiop79/pen/bxjGEe I want to apply this to the elements below (styled in flexbox), either the entire "row" or each i ...

Combine multiple SCSS files located in various directories into a single CSS file by using NPM

In my project, there are SCSS files stored in a "static" directory. Additionally, I have application components located in a separate directory, each containing its own SCSS file. I am seeking a way to compile all of these SCSS files into a single .css fi ...

Trouble arises when attempting to import React JSX project/modules from npm into an AngularJS TypeScript module

In the process of developing a proof-of-concept React framework/library, I aim to create a versatile solution that can be utilized in both React and AngularJS applications. To achieve this goal, I have initiated two separate projects: - sample-react-frame ...

Sending form data to the server using JavaScript: A step-by-step guide

Currently, I am dealing with the configuration of two servers. One server is running on React at address http://localhost:3000/contact, while the other is powered by Express at address http://localhost:5000/. My goal is to transmit form data as an object v ...

How to send data from a child component to a parent component in React without using

I've been working on a component called SelectInput for handling Select input in my project. Take a look at the code snippet below: 'use strict' import React from 'react' class SelectInput extends React.Component{ constructo ...