2

I have the following inline style object:

const simpleCarousel = {
   toggle: {
     ....
  },
  toggle_prev: {
    left: 0
  },
  toggle_next: {
    right: 0
  }
};

With the following standard CSS markup:

    <div className="toggle, toggle_prev">Prev</div>
    <div className="toggle, toggle_next">Next</div>

I want to use inline styles and combine the objects:

    <div style={ Object.assign(simpleCarousel.toggle, simpleCarousel.toggle_prev) }>
    Prev</div>
    <div style={ Object.assign(simpleCarousel.toggle, simpleCarousel.toggle_next) }>
    Next</div>

However, now toggle_prev and toggle_next both share left:0 & right:0

Question:

Short of immutable.js, in ES6/ES7 how can I combine my inline style objects immutably?

Update to Brandon request, this is not working:

  <div className="controls">
    <div style={ ...simpleCarousel.toggle, ...simpleCarousel.toggle_prev }>
     Prev</div>
    <div style={ ...simpleCarousel.toggle, ...simpleCarousel.toggle_prev }>
     Next</div>
  </div>

Module build failed: SyntaxError:

Ah HA!!! This works !!

 <div style={ { ...simpleCarousel.toggle, ...simpleCarousel.toggle_prev } }> Prev</div>
 <div style={ { ...simpleCarousel.toggle, ...simpleCarousel.toggle_next } }> Next</div>

2 Answers 2

1

You can use the object spread operator:

const a = { a: 1 };
const b = { b: 2, foo: "foo" };
const c = { foo: "override" };

// { a: 1, b: 2, foo: "override" };
const abc = { ...a, ...b, ...c };

// { a: 10, b: 2, foo: "override" };
const xyz = { ...abc, a: 10 };

More info: https://github.com/sebmarkbage/ecmascript-rest-spread

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

1 Comment

Unless I am misunderstanding you, this is not working for me: <div style={ ...simpleCarousel.toggle, ...simpleCarousel.toggle_prev } > ...
0

Another option would be to tweak your Object.assign call. It takes the properties from subsequent objects and adds them to the first one. So supply a new object to assign to each time and:

<div style={ Object.assign({}, simpleCarousel.toggle, simpleCarousel.toggle_prev) }>
Prev</div>
<div style={ Object.assign({}, simpleCarousel.toggle, simpleCarousel.toggle_next) }>
Next</div>

Should do what you want. Note the extra {} as the first parameter to Object.assign.

Comments

Your Answer

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