javascriptd3.jsobservablehq

D3 - How can I put an SVG into a DIV via a function?


To reuse code I want to put my SVG into a function and call it as needed. Once I select the DIV what is the appropriate construct to render the SVG inside it?

...

if (intLocations.includes(comm.location)) {
  const intActivities = d3.select('div#intActivities')
  intActivities.append(Pill(comm))
} else {
  const extActivities = d3.select('div#extActivities')
  actActivities.append(Pill(comm))
}

...

function Pill(comm) {
   const svgNode = d3.create('svg')
   svgNode
       .attr('width', 100)
       .attr('height', 100)
       .append('g')
       // More code to draw the figure using comm data.
   return svgNode;
   }

Solution

  • intActivities.append(() => Pill(comm).node()) should do the trick. Here's an example:

    <!DOCTYPE html>
    <html>
    
    <head>
      <meta charset="UTF-8">
      <script src="https://d3js.org/d3.v7.js"></script>
    </head>
    
    <body>
      <div id="my-div"></div>
    
      <script>
        d3.select('#my-div').append(() => square().node());
    
        function square() {
          const svg = d3.create('svg')
              .attr('width', 100)
              .attr('height', 100);
    
          svg.append('rect')
              .attr('width', 100)
              .attr('height', 100)
              .attr('fill', 'navy');
    
          return svg;
        }
      </script>
    </body>
    
    </html>

    Alternatively, you could pass your Pill function the div selection that you want to add it to.