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!
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.
To update our state, we use this. setState() and pass in an object. This object will get merged with the current state.
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.
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.
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>
);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With