Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React.js: how to make inline styles automatically update progress bar on state change

I have a progress bar that I am building in React.js and Zurb Foundation that I would like to reflect the current state. I understand that in the beginning I can set the width with something like this:

render: function() {
    var spanPercent = (this.props.a - this.props.b)/this.props.a + '%';
    var spanStyle = {
        width: spanPercent
    };
    return (
        <div className="progress">
            <span className="meter" style={spanStyle}></span>
        </div>
    );
}

however, when the value of props changes due to a state change, the inline style doesn't update even though the props value changes. Is there a best practice for doing this, such as using a callback, or placing the code somewhere else? I would appreciate any help!

like image 471
bryant Avatar asked Mar 11 '15 00:03

bryant


People also ask

Why is React not updating on state change?

State updates in React are asynchronous; when an update is requested, there is no guarantee that the updates will be made immediately. The updater functions enqueue changes to the component state, but React may delay the changes, updating several components in a single pass.

How do you make sure state is updated in React?

To update our state, we use this. setState() and pass in an object. This object will get merged with the current state.

What should getDerivedStateFromProps return to update a state in React?

getDerivedStateFromProps(props, state) is a static method that is called just before render() method in both mounting and updating phase in React. It takes updated props and the current state as arguments. We have to return an object to update state or null to indicate that nothing has changed.

How do you implement progress bar in React?

import React from "react"; import DummyContent from "./Components/DummyContent"; import ReadingBar from "./Components/ReadingBar"; function App() { return ( <div className="main"> <ReadingBar /> <DummyContent /> </div> ); } export default App; Now, your reading progress bar should be fully functional.


1 Answers

One solution is to put a key of the percentage on the element you want to update. That way when react checks to see what in the DOM has changed it sees that the key has changed and thus will rebuild the DOM for the element.

See example below:

render: function() {
   var spanPercent = (this.props.a - this.props.b)/this.props.a + '%';
   var spanStyle = {
          width: spanPercent
       };
   return (
      <div className="progress">
        <span key={spanPercent} className="meter" style={spanStyle}></span>
      </div>
);

}

like image 183
Andrew G. Avatar answered Sep 24 '22 08:09

Andrew G.