Subhojit
Subhojit

Reputation: 1541

Getting error while importing D3.js library in my React.js App

I'm facing an issue regarding importing the d3.js libraries properly in my react.js app. I am using import * as d3 from 'd3' to import everything and save it to d3 namespace but getting an error called - Cannot read property 'category20' of undefined. Any help regarding the issue ?

Click here to see the => Demo

import React from "react";
import * as d3 from "d3";
import donut from "./d3.donut.jsx";
import { render } from 'react-dom';

class PieCharts extends React.Component {
  constructor(props) {
    super(props);
  }
  componentDidMount() {
    let self = this;
    //let PieData=this.props.data;
    var getData = function() {
      var size = 4;
      var data = {};
      var text = "";
      for (var i = 0; i < size; i++) {
        data["data-" + (i + 1)] = Math.round(Math.random() * 100);
        text += "data-" + (i + 1) + " = " + data["data-" + (i + 1)] + "<br/>";
      }
      d3.select("#data").html(text);
      return data;
    };

    var chart = donut()
      .$el(d3.select("#" + self.props.id))
      .data(getData())
      .render();
  }

  render() {
    //console.log(this.props.data)
    return (
      <div>
        <div id={this.props.id} />
        <button className="btn btn-primary" onClick={this.props.clickActivity}>
          Simulate
        </button>
      </div>
    );
  }
}

render(<PieCharts />, document.getElementById('root'));

Upvotes: 1

Views: 1064

Answers (1)

Rupesh
Rupesh

Reputation: 61

Its syntax error. You are using d3 v5 so you need to follow the updated syntax

Use d3.scaleOrdinal(d3.schemeCategory20) instead of d3.scale.category20().
Use d3.pie instead of d3.layout.pie
Use d3.arc() instead of d3.svg.arc()

Upvotes: 1

Related Questions