The appearance of the React user interface in my app does not match what is displayed in the inspect element tool

Strange issue at hand. The progress bar in question appears like this:

1 export default function PercentageBar(props) {
2     return (
3         <div className="w-full h-1 my-1 bg-stone-200">
4             <div className={`h-1 bg-orange-500 w-[${props.percent}%]`} />
5         </div>
6     );
7 }

The styling is achieved using Tailwind CSS. To explain for those unfamiliar, the outer div spans the full width of the parent div, has a height of 1, top and bottom margin of 1, and is colored in a grayish hue. The inner div is then layered on top, also with a height of 1. The inner div is in orange and spans the width of props.percent (a percentage of the parent div's total width).

I have confirmed that props.percent is correctly passed in.

However, when props.percent dynamically changes during runtime, line 4 behaves strangely at times (irrespective of the specific percent value).

For instance, if props.percent was initially 48 and later becomes 52, Inspect Element shows:

<div className={`h-1 bg-orange-500 w-[52%]`} />

which is accurate. Yet, it renders as follows (a full bar)

<div className={`h-1 bg-orange-500 w-[100%]`} />

Moreover, there are instances where it renders as if props.percent is 0, post a change in the percent value. This issue persists regardless of attempts like hard refreshes, cache resets, etc., occurring sporadically and across various browsers. Sometimes the problem doesn't surface with repeated refreshing. Any insight into what might be occurring here? Much obliged!

Answer №1

I encountered a similar issue, but with the use of classNames. To address this, I passed the classNames from where I'm utilizing the component. This ensures that the component will re-render when props change. Additionally, I included the ! important keyword if anything alters your class. I hope this solution resolves your problem.

export default function PercentageBar({widthPercentage}) {
    return (
        <div className="w-full h-1 my-1 bg-stone-200">
            <div className={`h-1 bg-orange-500 ${widthPercentage}`} />
        </div>
    );
}
<PercentageBar widthPercentage={`!${w-[${props.percent}%]}`} />

Answer №2

Users working with Tailwind 3 (or Tailwind 2 in JIT mode) should note that dynamically creating classes is not possible as they will not be included in the final CSS output.

Instead of creating dynamic classes for your variable value, consider using a style prop to specify the width. Here's an example:

<div style={{width: `${someValue}%`}} className={'h-1 bg-blue-700'} />

Answer №3

Discovered the solution! Credit goes to Ed Lucas for guiding me in the right direction. He's absolutely correct - dynamically creating class names in Tailwind is not possible. For a detailed explanation, check out this link.

Although the style tag recommended by Ed didn't work for me, I came up with a different approach. I created a new function that uses a switch statement to generate continuous strings of class names based on the width value. Here's an example:

function getWidthClassName(percent) {
    switch (percent) {
        case 0:
            return 'w-[0%]';
        case 1:
            return 'w-[1%]';
        case 2:
            return 'w-[2%]';
        ...
        case 99:
            return 'w-[99%]';
        case 100:
            return 'w-[100%]';
        default:
            return 'w-[0%]';
    }
}

With this function in place, my progress bar code now looks like this:

export default function PercentageBar({percent}) {
    let widthClassName = getWidthClassName(percent);
    return (
        <div className="w-full h-1 my-1 bg-stone-200">
            <div className={`h-1 bg-orange-500 ${widthClassName}`} />
        </div>
    );

By statically constructing class names instead of dynamically doing so at runtime, Tailwind is satisfied and so are we.

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

Passing a unique data value from Ajax to PHP using Ajax and PHP techniques

Currently, I'm working with Google Charts to set up various line charts. These charts are using data from a MySQL database, which is retrieved through an Ajax call to a PHP script. Right now, I have everything working smoothly by manually inputting t ...

NewbieCoder is requesting clarification on the JQUERY smoothscrolling code, can anyone assist?

Can anyone provide an explanation of the functionality of the following JavaScript code? Specifically, I would like a breakdown of each line in this smooth scrolling API. $('a').click(function(){ //upon 'a' click, execute th ...

The error message is indicating that the property `match` is being attempted on an undefined object. This issue is puzzling as it does not reference any specific files or

I encountered an issue while working on my project: I kept receiving the error message "Cannot read property match of undefined." Cannot read property 'match' of undefined The error points to a specific line in polyfills.js: process.version.ma ...

The absence of a meta tag in the Wordpress head section

I keep getting an error from Lighthouse saying that I am missing both the viewport meta tag and description meta tag Does not have a <meta name="viewport"> tag with width or initial-scaleNo `<meta name="viewport">` tag found ...

What is the best way to style the currently selected option element in a select dropdown?

I am trying to change the font color of specific option elements within a select dropdown by adding style="color: #D4D4D4". When I apply this style directly to an option element like <option value="TEST" style="color: #D4D4D4">TEST</option>, it ...

Is it possible to utilize JSON in Struts 2 to bypass the necessity of tags and page mappings?

Lately, I've been pondering the concept of a design approach that utilizes unmapped pure HTML and JavaScript pages pulling JSON data from Struts 2. This means no action mappings are required, resulting in relative page references with minimal need for ...

Transform an angular1 javascript circular queue implementation for calculating rolling averages into typescript

I am currently in the process of migrating a project from Angular 1 to Angular 2. One of the key components is a chart that displays a moving average line, which requires the use of a circular queue with prototype methods like add, remove, and getAverage. ...

Verify modifications prior to navigating in React or Next.js

I have a simple Next JS application with two pages. -> Home page import Header from "../components/header"; const handleForm = () => { console.log("trigger"); }; export default () => ( <> <Header /> & ...

Error in Compass Compilation when encountering Unicode Characters

After compiling with Compass, I noticed that if I don't include @charset "UTF-8"; in my root scss file, the output looks like this: @charset "IBM437"; Even though my CSS output still displays the correct Unicode characters, such as: content: "ĐĂN ...

Can I leverage getStaticProps and getStaticPaths within a page component that employs dynamic routing without prior knowledge of the IDs?

I have created a fully static site generation (SSG) app where the backend cannot be accessed during build time. All the data is specific to user permissions, so I cannot specify paths in the getStaticPaths method required for dynamic routed components us ...

What is the process for transferring a web project to my local server?

I'm having trouble figuring out how to connect my web application to the server. I attempted to use the following code: res.sendFile(path.resolve('./public/index.html')); However, it seems to be not linking the components that are written i ...

Unable to display an image prior to its upload

I'm facing an issue with changing the image for my second data. It's not updating, but when I try it with the first data, it works fine. I'm unsure why this is happening and would appreciate any help in resolving it. Here is the form where ...

What are some ways to prevent Visual Studio from adding an extra space in JavaScript code during the build or rebuild process?

In my Visual Studio 2019 Enterprise setup, I have noticed that when I build or rebuild my ASP.net 4 MVC solution, my JavaScript files are regenerated by TypeScript. The issue is that the new JavaScript files always end up with a single trailing space after ...

Steps to create a div with a z-index of 1 that fills the entire height:

Looking at the image, I have a sidebar that opens over other elements (blue color) using z-index = 1. When the sidebar is open, I want to hide all other elements except for the sidebar. However, towards the end of the sidebar, I can still see other element ...

Change the class of the div when the first div is selected

My goal is to switch the class of the #klapp element (from .klapp to .klappe) whenever a click event happens inside the #label-it container, including when the #klapp element itself is clicked. The challenge is that I am not able to use unique IDs for each ...

Issue in Vuetify: The value of the first keypress event is consistently an empty string

I need to restrict the user from entering numbers greater than 100. The code snippet below represents a simplified version of my production code. However, I am facing an issue where the first keypress always shows an empty string result. For example, if ...

Ways to confirm an error message using Jest mock for throwing an error within a catch block

I'm having trouble mocking the catch block in jest for the code snippet throw Error(JSON.stringify(studentErrorRes));. While I can partially verify that an error is thrown, I'm unable to mock the error message properly. Typically, I use .mockReje ...

I am experiencing difficulty typing continuously into the input box in reactJS

In one of my components, I have the capability to add and delete input fields multiple times. <> <form onSubmit={optimizeHandler}> <div className="filter-container"> {conditions.map((condition, index) => ...

Implement push notifications on a React Js web app using Firebase

Trying to implement Firebase push notifications in my React JS application. I have been following the tutorials listed below: https://github.com/pavelpashkovsky/react-fcm Everything is working fine up to the point of receiving the token. However, when I ...

I am constantly reminded by React hooks to include all dependencies

Imagine I am using useEffect to pre-fetch data upon initial rendering: function myComponent(props) { const { fetchSomething } = props; ... ... useEffect(() => { fetchSomething(); }, []); ... ... } My linter is warni ...