0

I have an SVG constructed using d3, that depends on the value of an <input> element on the page. I'd like for the SVG to update whenever the input value has changed. There is simple reactivity demo in the tutorial. However, the example using d3 puts the code in onMount and this seems to break reactivity.

Here's an example:

<script>
    import { onMount } from 'svelte';
    import * as d3 from 'd3';
    
    var word = "Hello";
    let container;

    onMount(() => { d3.select(container).text(word); });
</script>

<p><input bind:value={word}></p>
<p>You typed "<span bind:this={container}></span>"</p>

You'll find that typing in the text box does not cause the text in the span to update:

A bonus would be for the SVG to only update after a delay, so that the user has time to finish what they are typing. (The real SVG is much heavier than the toy example above).

1 Answer 1

1

d3 depends on DOM access, whenever that is the case you usually can replace the onMount with a reactive statement ($:) that is guarded by a check on the DOM elements being used.

This only works correctly if you prevent additions and removals from the DOM to compound. This may not be the case with d3.

For this simple example you could do:

$: if (container) {
  d3.select(container).text(word);
}

REPL

Depending on what you are trying to do, you could also just ditch d3 and construct the SVG using Svelte.

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.