Home > Software design >  Using svelte actions to manipulate an html element with d3
Using svelte actions to manipulate an html element with d3

Time:08-31

this is somewhat related to my previous post where I learned a bit more about actions.

I have been trying to figure out how to work with this nifty feature but I seem to be a bit stuck in the past few hours.

In my Component I create an SVG viewbox like so:

<svg id="pitch" viewBox={`0 0 ${width} ${height}`} use:foo>

    </svg>

then drawPitch is this function:

function foo(node) {
        // the node has been mounted in the DOM
        let g = node.append('h1');
        g.text("This is the text I'd like to render to check that it works");
        return {
            destroy() {
                // the node has been removed from the DOM
            }
        };
    }

From what I've understood in the docs, the use:foo will pass the calling node to foo, so I thought directly appending svg elements to it should work. Do I need to update it somehow?

Here is a repl with reproducible code.

I get the following error:

Missing "./types/runtime/internal/keyed_each.js" export in "svelte" package

Thank you!

CodePudding user response:

I would expect the code in foo to start with d3.select(node), and everything to work based off that. Otherwise the DOM tree generated by d3 will not be connected to your document at all. Alternatively the resulting element (selection.node()) has to be appended to node at some point.

The error sounds highly unrelated and probably would require more context.

Note: You cannot add HTML directly to SVGs, SVGs are for canvas-like vector graphics, not document layouts. If you want to insert text, use the <text> element.

  • Related