omriman12
omriman12

Reputation: 1690

ReactJS - Embed Svg image using D3

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?

Upvotes: 0

Views: 1924

Answers (2)

grenzbotin
grenzbotin

Reputation: 2565

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.

Upvotes: 2

Tyler
Tyler

Reputation: 674

i think you can try append a tag before href

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

Upvotes: -1

Related Questions