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
Solving this problem is very simple.
Bad way
<div style={this.props.style} />
Good way
<div style={{ ...this.props.style }} />
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)
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.
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