简体   繁体   中英

Chart in d3js not showing up in react app

I am trying to follow the tutorial here but using react app. The chart is not showing up and I am not sure what I am doing wrong, please help. I am using d3 v7 and react 17. I get no errors but the buttons show up so the component is called correctly.

This is my component:

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

const PieChart = (props) => {
    const ref = React.createRef()
    useEffect(() => {
      draw()
    });

    // set the dimensions and margins of the graph
    const width = 450, height = 450, margin = 40;
    // The radius of the pieplot is half the width or half the height (smallest one). I subtract a bit of margin.
    const radius = Math.min(width, height) / 2 - margin;
    // set the color scale
    const color = d3.scaleOrdinal()
    .domain(["a", "b", "c", "d", "e", "f"])
    .range(d3.schemeDark2);
    // create 2 data_set
    const data1 = {a: 9, b: 20, c:30, d:8, e:12}
    const data2 = {a: 6, b: 16, c:20, d:14, e:19, f:12}
    const svg = d3.select(".PieChart")


    // A function that create / update the plot for a given variable:
    const update = (data) => {
        if (data == "data1"){
            data = data1;
        }else{
            data = data2;
        }

        // Compute the position of each group on the pie:
        const pie = d3.pie()
        .value(function(d) {return d[1]; })
        .sort(function(a, b) { return d3.ascending(a.key, b.key);} ) // This make sure that group order remains the same in the pie chart
        const data_ready = pie(Object.entries(data))

        // map to data
        const u = svg.selectAll("path")
        .data(data_ready)

        // Build the pie chart: Basically, each part of the pie is a path that we build using the arc function.
        u
        .join('path')
        .transition()
        .duration(1000)
        .attr('d', d3.arc()
        .innerRadius(0)
        .outerRadius(radius)
        )
        .attr('fill', function(d){ return(color(d.data[0])) })
        .attr("stroke", "white")
        .style("stroke-width", "2px")
        .style("opacity", 1)

    }
    
    const draw = () => {

        svg.append("svg")
        .attr("width", width)
        .attr("height", height)
        .append("g")
        .attr("transform", `translate(${width/2}, ${height/2})`);


        // Initialize the plot with the first dataset
        update("data1")
    };
    

    return <div ref={ref} >
            <button onClick={update("data1")}>Data 1</button>
            <button onClick={update("data2")}>Data 2</button> 
            <div className="PieChart" /> 
        </div>
}

export default PieChart

This is what I get, no graph

在此处输入图片说明

I think there are quite a few things that need to be fixed. First & foremost is the usage of ref . You have to do const ref = React.useRef() ie use useRef instead of createRef . Also, the ref has to be set to the svg element and not the div .

The 'almost' working code is here. https://codesandbox.io/s/flamboyant-heisenberg-vppny?file=/src/pie.js

I say almost because the chart does not render on page load! I do not know why (I am not very familiar with react). To render the chart, change the value of width or height from 450 to 451. I do not know why this works but it does.

One the page is loaded with the chart, the buttons & the chart transition work fine.

If you figure how to render the chart on page load, please let me know.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM