Steren
Steren

Reputation: 7909

How to update a web component's shadow DOM when its size changes?

I am developing a web component that renders some graphics on a <canvas>, that appended to the component's shadowRoot

I would like to re-size and re-render the canvas when the size of the element changes (e.g. its CSS width property is updated).

How to do so? Should I be using a ResizeObserver?

Upvotes: 1

Views: 1047

Answers (2)

leoplaw
leoplaw

Reputation: 192

I agree with the answer @Steren provided, but will add one more detail which might help others like me.

The component might default to a style display: inline and cause the resizeObserver not to work. So by setting it to dispaly: block the observer will be fired when the component resizes.

constructor() {
  super();
  const resizeObserver = new ResizeObserver(() => {
    // re-render my canvas
  });
  resizeObserver.observe(this);
  this.style.display = "block"
}

Upvotes: 0

Steren
Steren

Reputation: 7909

I ended up using a ResizeObserver in the constructor of my custom element:

constructor() {
  super();
  const resizeObserver = new ResizeObserver(() => {
    // re-render my canvas
  });
  resizeObserver.observe(this);
} 

Upvotes: 2

Related Questions