0

I am making a D3 circle pack layout.

    const BubbleChart = ({ bubblesData, height, width }: BubbleChartProps) => {
    
      const packData = (size: any) => {
        return d3.pack().size(size).padding(3);
      }
    
      const makeHierarchy = () => {
        return d3.hierarchy({ children: bubblesData }).sum((d:any) => d.count);
      }
    
      const makeBubbles = () => {
        const hierachalData = makeHierarchy();
        const packLayout = packData([width - 2, height - 2]);
        const root = packLayout(hierachalData);
    
        const svg = d3.create("svg")
        .attr("width", width)
        .attr("height", height);
    
        const leaf = svg.selectAll("g")
          .data(root.leaves())
          .enter().append("g")
            .attr("transform", d => `translate(${d.x + 1},${d.y + 1})`);
    
        leaf.append("circle")
        .attr("r", d => {
          const minValue = d3.min(bubblesData, (d) => d.count)
          const maxValue = d3.max(bubblesData, (d) => d.count)
          let scale = d3.scaleSqrt()
            .domain([0, maxValue as unknown as number])
            .range([0,d.r]);
          return scale(minValue as unknown as number);
          })
          .attr("fill", "#d9edf7")
  
        return svg.node();
      }
    
      return (
        <div id="chart">{makeBubbles()}</div>
      )
    }
    
 export default BubbleChart

The issue is I am not able to render svg.node() as the type pf svg.node() is Object. I am getting below error:

Objects are not valid as a React child (found: [object SVGSVGElement]). If you meant to render a collection of children, use an array instead.

Is there a way I can render this?

sg055322
  • 161
  • 2
  • 15

1 Answers1

1

Also ran into this problem. The solution is to use a ref to an html element and use ref.current.appendChild(svgObject).

Render SVGSVGElement in React JS without dangerouslySetInnerHtml

Another alternative

svgRef.current.replaceWith(svgObj);
return (
  <div>
    <svg ref={svgRef} />
  </div>
)
James
  • 110
  • 2
  • 6