Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why was mutating style deprecated?

Tags:

reactjs

The documentation in 0.13 and 0.14 both warn that mutating style has been deprecated, but don't mention why

Reusing and mutating a style object between renders has been deprecated

What should I do if I want to perform state-dependent animations on an element that css class-based animations can't handle? Clone the object each time?

New to react, help and advice much appreciated

like image 760
CheapSteaks Avatar asked Oct 23 '15 05:10

CheapSteaks


3 Answers

Solving this problem is very simple.

Bad way

<div style={this.props.style} />

Good way

<div style={{ ...this.props.style }} />
like image 94
Sedrak Ghukassyan Avatar answered Sep 23 '22 20:09

Sedrak Ghukassyan


You can work around this problem by copying the the previous style into a new variable and copying the previous style object.

Example:

Not Allowed

const {styleFromProps} = this.props;

const newStyle = styleFromProps['marginTop'] = '45px';

Allowed

const {styleFromProps} = this.props;

const newStyle = {...styleFromProps, marginTop: '45px'};

This way, you are not mutating anything, but just creating an new object from the previous one (i.e styleFromProps)

like image 33
HussienK Avatar answered Sep 22 '22 20:09

HussienK


Looking at the test case/expected error, you are correct and should be cloning the object.

Warning: `div` was passed a style object that has previously been
mutated. Mutating `style` is deprecated. Consider cloning it
beforehand. Check the `render` of `App`. Previous style:
{border: "1px solid black"}. Mutated style:
{border: "1px solid black", position: "absolute"}.

https://github.com/facebook/react/blob/fc96f31fade8043856eb7bc34c56598c4a576110/src/renderers/dom/shared/tests/ReactDOMComponent-test.js#L128

I would guess it's similar to the reasoning for props - it saves you from passing a mutable style object around everywhere and ending up losing a lot of the ease of reasoning that React is really good at helping you with.

The props object is now frozen, so mutating props after creating a component element is no longer supported. In most cases, React.cloneElement should be used instead. This change makes your components easier to reason about and enables the compiler optimizations mentioned above.

like image 28
Alex T Avatar answered Sep 22 '22 20:09

Alex T