What I'm trying to do is dynamically add in new elements and change their styles sometime in the future. So to do that, I tried creating an object that would go into the state and would contain two attributes that have an array value set to them: one being an array that holds the element itself and the other that holds the style associated with that.
But for some reason, even though I tried creating a copy of the object holding the two attributes (someone said to treat the state as if it's immutable on stackoverflow) and updating that, then setting the state to the new object, it still doesn't seem to update.
I also tried the solution from here, but it still gives the same problem.
var React = require('react');
var ReactDOM = require('react-dom');
var update = require('react-addons-update');
var Book = React.createClass({
getInitialState() {
return {
pages: {
pageElements: [], pageStyle: []
}
};
},
changeStyle: function (e) {
this.setState(update(this.state.pages.pageStyle[0],
{name: {$set: {position: 'absolute', transform: 'translate(50px,100px)'} }}));
},
componentDidMount: function () {
let pagesCopy = {
pageElements: this.state.pages.pageElements, pageStyle: []
};
pagesCopy.pageStyle.push({styles: {position: 'absolute'}});
pagesCopy.pageElements.push(
<img
key={0}
onMouseDown={this.changeStyle}
style={this.state.pages.pageStyle[0]}
src={'/pages/0'}
height="800px"
width="600px"/>);
this.setState({pages: pagesCopy});
},
render: function () {
return (
<div>
<section style={{position: 'relative', height:800, width:1200, margin: 'auto'}}>
{this.state.pages.pageElements}
</section>
</div>
)
}
});
ReactDOM.render(<Book/>, document.getElementById("content"));
I think the problem lies within the following line:
style={this.state.pages.pageStyle[0]}
where it's referencing the object directly. I think it's taking that value and setting that value to the style permanently and since there can only be copies of states, it can't see the updated value on the new object holding the two attributes. I also did research on how to get a reference to the array index so that it fetches it everytime when I update the state, but in the end, it ultimately just makes that value final and keeps it static (I think).
Note: the code is a super simplified version of a larger code, but the code I have here is the basic that's causing the problem