Using inline styles for progress bars in React

Struggling to apply styling to the element labeled as "progress", I've tried multiple options but just can't seem to get it right.

Any assistance or clues would be greatly welcomed! Here is the code snippet for the component:

  constructor(props) {
    super(props);

    this.state = {
      arrIterator: 0,
      counter: 0,
      sets: props.ids.sets,
      exercises: props.program,
      ids: props.ids
    }

    // Variable used to determine new round initiation --> Reset counter
    this.newRoundOn = ((this.state.exercises.length /this.state.sets) -1);

    // Calculates percentage for progress bar
    let barPercentage = ((this.state.arrIterator / this.state.exercises.length) * 100) +"%";

    this.style = {
      width: {barPercentage} 
    }
  }

  // Displays Progress Bar
  renderProgressBar() {
    return(
      <div className="card-panel" id="progression-panel">
      <div className="row">
          <h5 className="col s8">Progression</h5>
          <h5 className="col s4 right-align">{this.state.arrIterator +1} / {this.state.exercises.length}</h5>
      </div>
      <div className="progress" style={style}>
          <div className="determinate"></div>
      </div>
  </div>
    );
  }

Answer №1

To update the progress bar, you need to adjust the state accordingly. Use the componentDidUpdate method to check for any property changes and then set a new value for barPercentage:

It is recommended to avoid passing props directly to state.

constructor() {
   this.state = {
     barPercentage: 0
   } 
}

componentDidUpdate(prevProps) {
  // Determine when a new round begins -> Reset counter
  this.newRoundOn = ((this.props.exercises.length / this.props.sets) - 1);

  // Calculate percentage for progress bar
  let barPercentage = (this.props.arrIterator / this.props.exercises.length) * 100;

  if (this.props.arrIterator > prevProps.arrIterator) {
    this.setState({ barPercentage })
  }
}

render() {
  return (
    // [...]
    <div className="progress" style={{ width: `${this.state.barPercentage}%` }}>
      <div className="determinate"></div>
    </div>
    // [...]
  )
}

Answer №2

  constructor(props) {
    super(props);

    this.state = {
      arrIterator: 0,
      counter: 0,
      sets: props.ids.sets,
      exercises: props.program,
      ids: props.ids
    }

    // Determine when to start a new round and reset the counter
    this.newRoundOn = ((this.state.exercises.length / this.state.sets) - 1);

    // Calculate progress bar percentage
    let barPercentage = ((this.state.arrIterator / this.state.exercises.length) * 100) + "%";

    this.style = {
      width: {barPercentage} 
    }
  }

  // Render Progress Bar
  renderProgressBar() {
    return(
      <div className="card-panel" id="progresjon-panel">
      <div className="row">
          <h5 className="col s8">Progress</h5>
          <h5 className="col s4 right-align">{this.state.arrIterator + 1} / {this.state.exercises.length}</h5>
      </div>
      <div className="progress" style={style}>
          <div className="determinate"></div>
      </div>
  </div>
    );
  }

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

React in 2022 has encountered an unexpected expression when it was expecting either an assignment or function call

I am having difficulty updating a chart with values received from an API. I am unsure about how to adjust the useEffect hook in my code. Any advice would be greatly appreciated. Here is a snippet of my code: import React, { useEffect, useState } from &quo ...

I'm having trouble understanding the distinction between this.query and this.query.find(). Can you explain the difference to me?

Currently, I am working on a MERN tutorial where I am developing a full E-commerce application. This is the class that handles querying and various other tasks. constructor(query, querystr) { this.query = query; this.querystr = querystr; con ...

How do I iterate through my state in React Redux?

Currently, I am delving into Redux by creating a to-do list in React. I have been pondering on the utilization of the map function to iterate over the state so that I can display the data stored within different div elements. Here is my initial state: cons ...

An error arises in Typescript when the reducer state does not update upon clicking. The error message indicates that the properties 'state' and 'dispatch' are not recognized on the type 'UserContextType | null'

Having recently delved into typescript with react, I've encountered some issues. Despite trying various solutions, the state doesn't seem to work properly and I keep getting a typescript error stating: Property 'state and dispatch' does ...

Sending massive file using axios in React and .NET Core

I am facing an issue when trying to upload a large file (100MB) on the iis server. The code below works perfectly fine with smaller files (13MB), but I encounter the following error message when attempting to upload larger files: Access to XMLHttpRequest ...

Different Types of Props for Custom Input Components using React Hook Form

Struggling with creating a custom FormInput component using React Hook Form and defining types for it. When calling my component, I want to maintain autocompletion on the name property like this ... <FormInput control={control} name={"name"}& ...

What are effective solutions to reduce the increasing Next.js bundle size caused by dynamic component lookup?

tldr: For more information, please visit the repository. The common.js file includes all dependencies, even though only one is used on the current page. http://localhost:3000/components/ComponentOne http://localhost:3000/components/ComponentTwo Live dem ...

How to enhance a class in JavaScript by adding a dynamic property

Within my code, I've defined a class which looks like this: class classA { id: number; name: string; constructor(data){ this.id = data?.id || 0; this.name = data?.name || ''; } } What I aim to do now is add ...

Express JS does not return form data, resulting in a null value

I am encountering an issue while trying to send data from React to Express. I have an array of images that need to be sent, but due to the inability to send a single image as a test, I will need to clarify the scenario. To simplify the testing process, I h ...

Tips for Customizing the Appearance of Material UI Select Popups

My React select component is functioning properly, but I am struggling to apply different background colors and fonts to the select options. https://i.stack.imgur.com/kAJDe.png Select Code <TextField fullWidth select size="small" nam ...

Obtain the number of elements rendered in a React parent component from a switch or route

I'm currently working on a component that is responsible for rendering wrapper elements around its children. One challenge I'm facing is determining which elements are actually being rendered as children. I've implemented functions to ignore ...

Using shadow effects on the <Grid> component with Material UI

Is there a way to implement the box-shadow property on a <Grid> component in Material UI? I've gone through the official documentation regarding Shadows - Material UI, but I'm struggling to grasp how it can be applied to a <Grid>. De ...

At what point does a vulnerability in a React or Angular library become a serious threat?

As a cybersecurity student, I have noticed numerous CVEs related to libraries used in React and Angular. One example is: │ Critical │ Prototype Pollution in minimist │ ├────────────── ...

What is the best technique for vertically aligning text within two divs placed side by side?

Thank you for taking the time to read this. I have a piece of code similar to the one below. While using line-height works when there is only one line of text, it becomes problematic when the comments section contains multiple lines. I am wondering what w ...

Adjust the size of a div element dynamically to maintain the aspect ratio of a background image while keeping the

Utilizing the slick slider from http://kenwheeler.github.io/slick/ to display images of varying sizes, including both portrait and landscape pictures. These images are displayed as background-image properties of the div. By default, the slider has a fixed ...

Loading Web Applications Screen

My web app contains multiple tree views. Upon loading the page, I first see the unordered lists before the styling of the trees is displayed in the DOM after a brief delay. Is there a method to mask the web app with a spinner placed in the center of the s ...

Is there a way to prevent the arrow up and down events from functioning on the MUI Menu?

My menu features a text field and a button. The text field is of type number, so ideally when I click on it and use the arrow up and down keys, the value should increase and decrease. However, instead of that functionality, the menu items are being selecte ...

Building a bridge between React Native and MongoLab

I am currently in the process of developing a React Native application for iOS that will require querying a database. After some research, I have chosen to use MongoLab. Upon reviewing MongoLab's documentation, it is suggested to utilize the MongoDB D ...

Obtaining User Input in React JS within the Fetch Statement

I've written a code to fetch weather data from an API. Currently, the location is set to "chennai" in the link provided. I'd like to make this location user-dependent. How can I achieve this using React? import React,{useState,useEffect} from ...

Tips for modifying the "width" of a style within an HTML template implemented in a NodeJs express application

Currently, I am facing a challenge in dynamically adjusting the width value for a <div> element serving as a coloured bar within an HTML template used for PDF generation. While I can successfully set other values using something like {{my_value}}, ap ...