How to display percentage value on ReactJS Material UI progress bar

For displaying the progress completed in numbers, I utilize the Linear Determinate component. Take a look at the image below to see how it appears.

Answer №1

Check out the sample on codesandbox for an example of how Materiaui supports progressbar implementation.

Answer №2

It appears that the progress bar you are looking for may not be available in Material UI based on the image provided.

You might want to consider utilizing React Bootstrap, a package that offers similar functionalities to achieve your desired progress bar.

For more information, you can refer to this link -

Answer №3

If you're still looking for a solution, I was able to tackle this using the magical powers of React.createPortal. 😊

Here's how you can make it work:

  • Firstly, ensure to add a reference to your progress bar (note: you can't use useRef if you want your label to be initialized on mount; opt for element local state instead - like
    useState<HtmlElement | undefined>()
    )
  • Incorporate the following snippet inside your progress bar component:
ref={(el: HTMLElement) => setElement(el)}
  • Now, create a separate component that will contain your label. Make sure to pass down the element from your local state (IMPORTANT: pass the child element from your node, not the parent -> el={element.firstElementChild}).
  • Utilize createPortal to seamlessly integrate this component as a child of element.firstElementChild, which is essentially the progress bar. Here's a glimpse of my code for achieving this:
// In my scenario, I ensured the HTML code for my label has an absolute position so I could position it to the far right of my progress bar.
const MyLabel: FC<{ el: Element; extraLabel: string }> = ({ el, extraLabel }) => {
  return (
    <>
      {createPortal(
        <>..your HTML code for your label..</>, 
        el,
      )}
    </>
  );
};

Check out how it looks in action:

https://i.stack.imgur.com/tlsqT.png

Hope this helps! 🌟

To delve deeper into the wonders of React.createPortal and understand its sorcery, here's the official documentation: https://reactjs.org/docs/portals.html

Warm regards, Audrey - Senior FullStack Developer

Answer №4

To visually represent the progress, you can show this.state.completed, indicating the percentage value. To enhance its appearance, consider adding some styling options. Additionally, for clarity, you may choose to append a % symbol at the end since it represents a numeric value.

Answer №5

Check out these unique material-ui custom styles combined to create the desired component:

import React from "react";

import { withStyles } from "@material-ui/styles";
import { lighten, Box, LinearProgress, Typography } from "@material-ui/core";

interface Props {
  color?: "primary" | "secondary";
  hex?: string;
  value?: number;
}

/**
 * CustomProgressBar -- atom
 * A customized material-ui progress bar.
 * @param {'primary' | 'secondary'} color Choose between primary or secondary colors.
 * @param {string} hex Override color choice with a hex value.
 * @param {number} value The value for the progress bar, ranging from 0-100.
 * @return {JSX} React component
 */
const CustomProgressBar = ({ color, hex, value }: Props) => {
  let internalColor: string;

  if (typeof hex === "undefined") {
    internalColor = "#3f51b5";
  } else if (typeof hex !== "undefined" && /^#[0-9A-F]{6}$/i.test(hex)) {
    internalColor = hex;
  } else {
    throw new Error("Invalid hex prop -- please use a hex string.");
  }

  if (typeof value === "undefined") {
    value = 0;
  } else if (typeof value === "number" && value < 0) {
    throw new Error(
      "Invalid value prop -- please use a number more than or equal to 0."
    );
  } else if (typeof value === "number" && value > 100) {
    throw new Error(
      "Invalid value prop -- please use a number less than or equal to 100."
    );
  }

  // Styling based on material-ui docs
  const StyledLinearProgress = withStyles({
    root: {
      height: 20,
      width: "100%",
      backgroundColor: hex ? lighten(internalColor, 0.5) : undefined,
      borderRadius: "10px"
    },
    bar: {
      borderRadius: 20,
      backgroundColor: hex ? internalColor : undefined
    }
  })(LinearProgress);

   // Custom color adjustment
  const WhiteTextTypography = withStyles({
    root: {
      color: "#FFFFFF"
    }
  })(Typography);

  return (
    <Box position="relative" display="inline-flex" style={{ width: "100%" }}>
      <StyledLinearProgress
        color={hex ? undefined : color}
        variant="determinate"
        value={value}
      />
      <Box
        top={0}
        left={0}
        bottom={0}
        right={0}
        position="absolute"
        display="flex"
        alignItems="center"
        justifyContent="center"
      >
        <WhiteTextTypography variant="body2">{`${value}%`}</WhiteTextTypography>
      </Box>
    </Box>
  );
};

export default CustomProgressBar;

For an example in action, visit: https://codesandbox.io/s/stack-51254333-progressbar-x7j5m?file=/src/App.tsx:0-2390

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

No acknowledgment from command

Why doesn't the bot respond when I run this command? There are no errors. Do I have the role that matches in r.id? client.on('message', async message => { // Check if the user has a role with an id if(message.author.bot) return; ...

Challenges with uploading files using jQuery

Click here to upload a file I'm trying to create a feature where users can choose an image and have it displayed in place of the "trees" image. Feeling stuck, I could really use some guidance. Check out the code below: <div class="user-editab ...

The process of departing a SocketIO room and switching to a different room logic

I am wondering how I can leave the Room when I click on a new Room Here is what my page looks like: The list on the left side is from the MySQL Server and it displays a list of my chats. Each Room name has an id value which corresponds to the room name, ...

What is the best way to display a series of interconnected tables in a specific order within MySQL using recursion?

Given: table dependencies listed in sequence (Generated by MySQL Forward Engineer script) tableA, NULL tableB, NULL tableB, tableA tableC, NULL tableC, tableA tableD, NULL tableD, tableC I am working with a MySQL database containing over 40 relational tab ...

Floating division element above responsive divisions

element, I am in the process of developing a straightforward online card interface. In this interface, there will be a user profile picture displayed above some details about that user. However, to achieve this layout, the profile picture must appear hove ...

Tips for saving and accessing the value of an md-select ng-model in an AngularJS dialog?

Currently, I am utilizing a template to populate an md-dialog box: The procedure for displaying the dialog: $scope.showDialog = function(element) { var parentEl = angular.element(document.body); $mdDialog.show({ template: element, scope: $scope, pr ...

Transmitting keys and data from Sails.js to Angular via streaming

In my current setup, I am using an angular frontend to fetch data from a sails backend through the sails-mysql adapter and display it in a ui-grid. However, due to the large size of the dataset, there is a noticeable delay in loading the data before the pa ...

What is the optimal location for storing JSON data while dynamically loading via AJAX?

Let's imagine a scenario where there is an HTML page hosting a dynamic modal box. Clicking on different links within the page triggers the modal to open, each showing different content based on the clicked link. The dialog contents are fetched using A ...

What is the best way to showcase an image in a React.js application?

I have utilized the import { Avatar } from '@material-ui/core'; in order to showcase an image using the avatar feature. const TheHeader = () => { let _UsersId = localStorage.getItem("UsersId") const classes = useStyles(); const ...

The proper method for utilizing the clipped prop on the <v-navigation-bar/> component within Vuetify is as follows

Looking for the correct way to apply the clipped prop to <v-navigation-draw/> in a Vuetify application in order to ensure that the navigation drawer sits below the app-bar. Here is what I have tried so far. Started with a new project: $ vue create ...

Transforming an object into an array of objects with the power of JavaScript

Looking to transform an object with the following structure: { From: {"A","B","C"}, To: {"A1","B1","C1"}, value: {1,2,3} } I need to convert this array: [ {from: "A" ,to: "A1" , value: 1 }, {from: "B" ,to: "B1" , value: 2}, {from: "C" ,to: "C1" ...

Conceal the Div containing the specified class

I was hoping to hide the first DIV if the second DIV is displayed on the front end, and vice versa upon page load. If the first DIV is set to 'block,' then the second DIV should be set to 'none.' And If the second DIV is set to &apos ...

Issue with Dropdown Menu functionality while using multiple dropdown options

I am currently experimenting with dropdown menus from W3Schools and have encountered an issue when trying to implement two dropdown options. The code works fine for a single dropdown, but when I try to add a second one using GetElementsByClassName instead ...

Using JavaScript's DOM manipulation to switch out one HTML tag for another

As a newbie to javascript and DOM, I'm facing an issue with manipulating DOM elements using javascript in the given HTML code. <html> <head> <title>Testing</title> </head> <body> <marquee direction=up heig ...

Dim the brightness of an image on Internet Explorer

I discovered this code on another site and it functions flawlessly in Chrome and FF, however, IE (version 11.0.9) doesn't seem to like it. -webkit-filter: grayscale(0%); -moz-filter: grayscale(0%); -o-filter: grayscale(0%); filter: grayscale(0%); fil ...

Notifying a Child Component in React When a Props-Using Function Resolves a REST Call

When I submit an item or problem, I trigger a function in the parent component that has been passed down to the child component as props. After sending my information, I want to clear the input fields. The issue is that I am clearing the input fields immed ...

Combining multiple Float32Arrays to create a single Float32Array

I need help creating a function that can flatten multiple Float32Arrays into one large Float32Array const first = new Float32Array([1,2]); const second = new Float32Array([3,4,5]); const third = new Float32Array([6,7,8,9]); const chunks = [ ...

Adjust the internal state within a Vue3 component using a window function

Creating a "Loader" component that is fully independent and functional just by being included in the layout requires exposing some methods for use. Here is the code I have come up with: <script setup> let active = false; function show() { active ...

Run a series of Mocha unit tests based on the outcomes of previous test results

Currently, I am in the process of writing unit tests for a NodeJS application that I am developing. In relation to some unit-testing logic, I have a question. Imagine if the application first creates a "Group" for users, followed by creating individual Us ...

Ways to retrieve a variable within the init() function

My current project involves using datatables along with ajax to display information dynamically. Below is the code snippet I am working with: // Setting up the module var DatatableAdvanced = function() { // Examples of Basic Datatables var _c ...