Svelte: bind:width bind:height

Created on 6 Dec 2017  Â·  2Comments  Â·  Source: sveltejs/svelte

So apparently I'm not the only one who does this sort of thing:

https://twitter.com/shancarter/status/938185099140415493

It's very useful, particularly in the context of dataviz, to be able to get the dimensions of an element. I'll often have something like this:

<:Window on:resize='handleResize()'/>

<div ref:container>
  <svg ref:svg>
    <!-- dataviz using {{width}} and {{height}} somehow goes here -->
  </svg>
</div>

<style>
  ref:container {
    width: 100%;
    height: 400px;
  }
</style>

<script>
  export default {
    oncreate() {
      this.handleResize();
    },

    methods: {
      handleResize() {
        const { container } = this.refs;
        this.set({ width: container.offsetWidth, height: container.offsetHeight });
      }
    }
  };
</script>

It's annoying boilerplate, especially if you have several of these. You could create a helper component — example 1, example 2 allowing percentage heights — but that's annoying too.

A really nice solution might be to add width and height element bindings:

<div bind:width bind:height>
  <svg ref:svg>
    <!-- dataviz using {{width}} and {{height}} somehow goes here -->
  </svg>
</div>

<style>
  div {
    width: 100%;
    height: 400px;
  }
</style>

No more boilerplate. In particular we don't have the annoyance of having to add an oncreate handler just to call a method.

Under the hood this could use this fiendishly clever solution (used in react-resize-detector, giving way to ResizeObserver when it's ready.

enhancement proposal

Most helpful comment

Implemented in 2.4.0. Has a couple of caveats: it doesn't work with void elements or children of SVGs, and <svg> itself can only have clientWidth and clientHeight (not offsetWidth or offsetHeight). The compiler will throw an error if you try any of those.

All 2 comments

Is this going to be problematic if there are already height and width data variables someone might be using for something else?

Update: ignore this. No problem at all.

Implemented in 2.4.0. Has a couple of caveats: it doesn't work with void elements or children of SVGs, and <svg> itself can only have clientWidth and clientHeight (not offsetWidth or offsetHeight). The compiler will throw an error if you try any of those.

Was this page helpful?
0 / 5 - 0 ratings