0

I'm trying to assign styles to an object. Initial code was

targetEl.style.top = `${top}px` ;
targetEl.style.display = 'block';
targetEl.style.background = `url(${this.props.imgSrc}) no-repeat`;
targetEl.style.backgroundSize = "1800px 900px";

I tried to use es6 destructuring and rewrote the code like this:

targetEl.style = {...targetEl.style, 
                      top:`${top}px`, 
                      display: 'block', 
                      background: `url(${this.props.imgSrc}) no-repeat`, 
                      backgroundSize:  "1800px 900px" };

But for some reason it does not seem to work. What am I doing wrong?

Sooraj
  • 9,717
  • 9
  • 64
  • 99

2 Answers2

3

You are not using destructuring, you are using experimental spread syntax in an object literal which creates a new object. You might be used to that when working with immutable data frameworks, but here you really want to assign properties of the targetEl.style CSS declaration object. You do not want to replace the whole .style object with a new one.

Try Object.assign with a plain literal:

Object.assign(targetEl.style, {
    top: `${top}px`, 
    display: 'block', 
    background: `url(${this.props.imgSrc}) no-repeat`, 
    backgroundSize: '1800px 900px'
});
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
0

As a side note, it's a bit more efficient without Object.assign:

const s = targetEl.style; 
s.top = `${top}px`; 
s.display = 'block'; 
s.background = `url(${this.props.imgSrc}) no-repeat`; 
s.backgroundSize = '1800px 900px';

but even more efficient to assign them all at once (How can I set multiple CSS styles in JavaScript?) :

targetEl.style.cssText += `; top = ${top}px, display = 'block', 
    background = url(${this.props.imgSrc}) no-repeat, backgroundSize = '1800px 900px'; `;
Slai
  • 22,144
  • 5
  • 45
  • 53