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?

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

9 Comments

I use Babel, so I will give this a try. No need for jQuery anymore then.
Alternatively, you could use Object.assign if you polyfill it: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
Object.assign sounds good, but it seems to be unsupported by any browser but firefox - do I get this wrong?
That's why I said you'd have to polyfill it. Babel does this as well with the right config.
OK, now I see. Thank you!
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.