d3.jsbrushsvelte

Svelte and D3 brush


I'm struggling to understand how to use Svelte with something like D3's brush project. Svelte operates using a declarative approach. In the area chart example the SVG for lines is written out in the template HTML. To do this with D3 you would use Javascript function calls to select an element and call another function to modify the DOM. In the aforementioned chart example the D3 scaled library is only used to generate the axis array but the HTML itself is managed by Svelte. It makes sense Svelte works this way - building things up with function calls would be a lot less clean, but I can't figure out how to do this with the brush. How can I declaratively build up the brush HTML inside of my Svelte template, and how would this affect things like brush events? Would it rather be best to just use the brush functions inside of say onMount and sort-of tie change events to local Svelte variables?


Solution

  • I managed to do this myself https://svelte.dev/repl/00f726facd434b978c737af2698e0dbc?version=3.12.1

    As Mikkel said above, the way Svelte is designed doesn't play well naturally with something like D3. As I see it you have two options: try to wire D3 events into Svelte's reactive variables, or try to implement the functionality yourself.

    I opted for the second version. I took the HTML and CSS that D3 Brush created, adding a mouse handler to the carets, and tied all the variables together reactively. (The last part I did very messily. Would appreciate any feedback on doing this cleaner from other Svelte users).