Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React how to update style coordinates

Whenever I try to dynamically update some component in react, like for instance, position of the object on mousemove, it does throw an error:

Warning: `div` was passed a style object that has previously been mutated. Mutating `style` is deprecated. Consider cloning it beforehand.

How is this then possible to do any sort of dynamic stuff like interactive games in react if I cannot update object style props in any way. As for cloning the node that Reactjs suggests, it is not explained anywhere how to achieve the same result with cloning elements.

https://facebook.github.io/react/docs/top-level-api.html#react.cloneelement

This isn't at all helpful.

My issue is that on mouseup event (users wants to drop the piece), i would like to update the style props for the new values taken from updated state property, i.e within the render function.

<ComponentOne style={{left: this.state.left, top: this.state.top}} />  
like image 877
bodhihammer Avatar asked Oct 18 '22 14:10

bodhihammer


1 Answers

This warning is coming because left or top being NaN. Initialize your left or top to zero or some value in getInitialState Function.

  getInitialState: function() {
    return {
      left:0,
      top: 0
    };

Also cloning React-Element won't help you here. Warning is saying you have to clone your style object when you are making changes to it. Which can be done as

var style1 = {myProp: "value"};
var style2 = Object.assign({}, style1, {newProp:"newValue"}); 

Instead of setting them directly as

<ComponentOne style={{left: this.state.left, top: this.state.top}} /> 

Do in this way

var myStyle = {left: this.state.left, top: this.state.top};
<ComponentOne style={myStyle} /> 

And then based on your changes clone your myStyle object and add changed style properties to it.

like image 119
WitVault Avatar answered Nov 03 '22 09:11

WitVault