4

I'm using react.js and manage most of the style attributes via react, too. If I have a, for example, a success and an error button I want to apply a different background color to them.

Right now, I'm doing this with jQuery's extend function:

<span style={$.extend({background: 'forestgreen'},this.state.buttonStyle)}></span>

But I'm wondering if there is a better and maybe more readable solution for this. Any advice?

baao
  • 71,625
  • 17
  • 143
  • 203

1 Answers1

7

If you use a transpiler that implements the spread property proposal (such as Babel), you can write

style={{...this.state.buttonStyle, background: 'forestgreen'}}

instead.

Whether thats "better" or more readable is likely subjective.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • I use Babel, so I will give this a try. No need for jQuery anymore then. – baao Jul 22 '15 at 16:22
  • 1
    Alternatively, you could use `Object.assign` if you polyfill it: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign – Felix Kling Jul 22 '15 at 16:24
  • Object.assign sounds good, but it seems to be unsupported by any browser but firefox - do I get this wrong? – baao Jul 22 '15 at 16:28
  • That's why I said you'd have to polyfill it. Babel does this as well with the right config. – Felix Kling Jul 22 '15 at 16:30
  • OK, now I see. Thank you! – baao Jul 22 '15 at 16:30
  • Just merging objects is not enough when working with objects that contain CSS styles. There are shorthand properties, different letter casing etc which should be handled in correct order by the merging function. I'm looking for and haven't found yet a library that provides such a function. – sompylasar Sep 06 '15 at 15:19
  • Here's a library that does shorthand property expansion: https://github.com/kapetan/css-shorthand-expand , but this is not a complete solution. – sompylasar Sep 06 '15 at 15:25
  • Does Object.assign do recursive copy in depth as jQuery.extend({}, true, ...) ? – Fernando Gabrieli Jul 06 '17 at 15:23
  • @FernandoGabrieli: No. – Felix Kling Jul 06 '17 at 15:24