0

I am using react + webpack + d3.

I am building a dynamic SVG graph using D3. I can add image an SVG as follows in react:

import file_1 from '../../icons/03_file_reg.svg';

<image src={file_1}... />

This works. But I am trying to figure out how to do it with D3:

<svg id="test_svg">

</svg>  

d3.select("#test_svg").append("image").attr("xlink:href", {file_1}).attr("width", 10)....

This doesn't work.

I have seen another way to do it like so: how to use svg file for image source in D3

but his forces me to use static path to my svg instead of importing. is this the only way to do it? or can i use import some other way?

omriman12
  • 1,644
  • 7
  • 25
  • 48

2 Answers2

2

You can easily do it with imported SVGs as well:

import React, { useEffect } from "react";
import * as d3 from 'd3';

import SVGImage from './assets/example.svg';

const D3Image = () => {
  useEffect(() => {
    const svg = d3.select('#my-svg');
    svg.append("image")
    .attr("xlink:href", SVGImage)
    .attr("width", 100)
    .attr("height", 100)
  });

    return (
      <svg id="my-svg"></svg>
    );

}

export default D3Image;

with other words: get rid of the curly braces.

grenzbotin
  • 2,489
  • 1
  • 12
  • 14
-1

i think you can try append a tag before href

d3.select("#test_svg").append("a").attr("xlink:href", {file_1}).attr("width", 10)
Tyler
  • 644
  • 1
  • 5
  • 18