10

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

CheapSteaks
  • 4,091
  • 3
  • 28
  • 46

3 Answers3

8

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)

HussienK
  • 2,405
  • 2
  • 16
  • 14
7

Solving this problem is very simple.

Bad way

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

Good way

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

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.

Don
  • 576
  • 5
  • 18
Alex T
  • 1,182
  • 9
  • 10