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

The ideal scenarios for employing arrow functions

I've embarked on a new journey to learn React through an online course. However, one question has been lingering in my mind: At times, I invoke a function using an Arrow Function. For example: (shortened) const [color, setColor] = useState(); <but ...

What is the best way to arrange elements above and below each other in a single flexbox container?

Currently, I am facing a challenge aligning the number 238,741 and the letter N in Number. There is a padding between the Prize Pool div and the Number Active div. All of these elements are enclosed within a parent container with display set to flex and fl ...

Animating lines with JQuery beneath navigation links

Currently in the process of revamping my portfolio website, and it's still a work in progress. Recently stumbled upon a jquery tutorial that enables a line to animate under anchor elements on hover, which I find quite intriguing. However, I am facing ...

Despite utilizing the .img-fluid class, the image remains incompatible with the parent div and does not fit properly

So, I'm currently working on a test code where my aim is to fit an image into the parent div using Bootstrap 5. However, I'm facing a challenge where the image leaves a noticeable gap width-wise, despite using the .img-fluid class. You can see th ...

How to make browsers refresh cached images

.button { background: url(../Images/button.png); } Issue: To improve performance, static content on the website is cached with expiration headers. However, when an image changes, users must manually refresh their browser cache (Ctrl+F5 in IE). ...

Tips for manipulating fixed elements while navigating through the window's content

I am currently working with Materialize CSS (link) and I'm trying to figure out how to move select content while scrolling the page or when the window is scrolling. However, the example code I've implemented doesn't seem to be working. Is th ...

Troubleshooting scope evaluation in AngularJS within style tags on IE9 not functioning

My issue involves a div block with a style attribute that includes left:{{left}}px; and right:{{right}}px. Even though $scope.left and $scope.right are being updated, my item still doesn't move as expected. I have created a fiddle to demonstrate th ...

Is there a way to ensure that the useEffect hook only runs after the useNavigate hook has been utilized? How can I prompt the initial render to occur only following the useNavigate

After using the useNavigate hook, how can I ensure that useEffect runs and triggers an initial render in my component? Within the App.js component, which serves as the homepage with the "/" path, the following code is implemented: const [contact ...

Ensure that the navigation menu is consistently displayed properly, without any of its contents extending beyond the

I am experiencing an issue with the navigation menu on my website. Everything looks great in normal view, but when I resize the browser window to a smaller width, the menu ends up overflowing below the main content. I want the navigation menu to always dis ...

Utilizing React JS with Material-UI Autocomplete allows for seamlessly transferring the selected item from the renderInput to the InputProps of the textfield component

Exploring the functionality of the updated version of Autocomplete, my goal is to ensure that when an element is chosen from the dropdown menu, the input format of the text field will be modified to accommodate adding a chip with the selected text. Is the ...

Switch between using the useState hook by toggling it with the MUI Switch

Looking to implement a custom Dark Mode feature for a specific element on my create-react-app website using MUI. I have successfully implemented the Switch to change the state on toggle, but I am having trouble figuring out how to toggle it back and fort ...

How to automatically refresh a page when the URL changes with Next.js router?

On my page, users have the option to narrow down their search using filters. However, there is an issue where if a user selects a filter for "rent" or "buy", the URL does not automatically refresh to reflect the changes. Even though the changes are reflect ...

React SlideMenu will not close when a link is clicked

I am facing an issue with my off-canvas menu, which slides in when the variable isOpen is set to true. However, the problem arises when trying to slide it back out upon clicking a Link to navigate to another page. Instead of sliding out, the mobile menu oc ...

The MUI persistent drawer navigation bar becomes dysfunctional when accessing a specific route

Exploring the MUI library for the first time, I successfully created a navigation bar that functions properly for one route (Dashboard). However, when attempting to implement it on the candidate route, it collapses as shown in this Screengrab of collapsed ...

The table's content extends beyond the confines of the page

I have an HTML page where I am embedding an SSRS report. The report extends beyond the page as shown in the image below: This is the table that is generated: <table cellpadding="0" cellspacing="0" id="ctl00_MainContent_FiveYearReportViewer_fixedTable" ...

Personalizing CSS for a large user base

My website allows users to choose themes, customize background, text, and more. I am seeking the best method to save all of these changes. Is it preferable to use a database read or a file read for this purpose? Any recommendations are greatly appreciate ...

The issue with the <Button> component not properly linking in next.js

Having trouble with a button wrapped inside a custom Navbar component. The code snippet in question is: <NavBtn> <Link href="/contact" passHref> <Button> Contact Me </Button> </Link> & ...

How can I automatically check all checkboxes in a row when a material table is loaded and uncheck them when clicked?

I have been working on a project using React Material Table and I am trying to figure out how to make the "select all" checkbox default checked when the page is loaded. Additionally, I want the ability to deselect any checkbox if needed. I attempted to use ...

Is there a Wordpress floating bar similar to the one seen on 9gag?

After browsing through some posts on stackoverflow, I noticed that my website is not responding as expected. You can check out my site here: To troubleshoot, you can examine the source code and utilize Firebug to inspect the css and javascript being used ...

Struggling to constrain a TextField component from material-ui and encountering an issue with the inputRef

Currently, I am attempting to restrict the length of an autocomplete textfield within my project. However, when I apply InputProps={{ maxLength: 2 }}, it throws an error stating that my inputRef.current is null. Even though I have set the ref in the inputR ...