Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
175
rated 0 times [  182] [ 7]  / answers: 1 / hits: 79580  / 10 Years ago, tue, july 22, 2014, 12:00:00

I'm quite new to React.JS and I am in the process of experimenting by building a masonry-style layout.


I render each element to the DOM, then I need to loop over each item and apply x and y positions based on the preceding elements.


The initial model looks like this:


[
{
"title": "The Forrest",
"description": "some cool text",
"imgSmallSrc": "/img/img4-small.jpg",
"imgAlt": "Placeholder image",
"tags": [
"Design",
"Mobile",
"Responsive"
],
"date": 1367154709885,
"podStyle": {
"width": 253
}
}
]

(I've only shown one item to keep things short).


Once I complete the loop and have my x and y data I want to apply this to the podStyle object. I call setState() with the following data:


[
{
"podStyle": {
"x": 0,
"y": 0,
"height": 146,
"width": 253
}
}
]

This seems to remove all current data from the model and leave me with just the podStyle data. Am I misunderstanding how this merge works?


More From » reactjs

 Answers
14

If your state is an object:



getInitialState: function() {
return { x: 0, y: 0 };
}


you can use setState to set individual keys on that object:



this.setState({ x: 1 }); // y still == 0


React does no intelligent merging of your state; for example, this does not work:



getInitialState: function() {
return {
point: { x: 0, y: 0 },
radius: 10
};
}

this.setState({point: {x: 1}});
// state is now == {point: {x: 1}, radius: 10} (point.y is gone)


[Edit]



As mentioned by @ssorallen, you can use the immutability helpers to get the effect you're after:



var newState = React.addons.update(this.state, {
point: { x: {$set: 10} }
});
this.setState(newState);


See this JSFiddle for an example: http://jsfiddle.net/BinaryMuse/HW6w5/


[#70094] Monday, July 21, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
armandoh

Total Points: 208
Total Questions: 94
Total Answers: 112

Location: South Sudan
Member since Sun, Jul 11, 2021
3 Years ago
;