Importing d3 in react JS component file

Viewed 2666

I used the answer from this post and did import d3Js from 'https://d3js.org/d3.v3.min.js'; but now I am getting this error - Failed to compile. ./src/components/StreamGraph.js Module not found: Can't resolve 'https://d3js.org/d3.v3.min.js' in 'C:\Users\...\src\components'

React app has v6 installed through npm but I want to import v3 for some visualizations. I am trying to do a stream graph but not able to import d3 v3.

This is the code template I need to run:

import React, { Component } from "react";
import d3Js from 'https://d3js.org/d3.v3.min.js';
// import * as d3 from 'd3';
import './StreamGraph.css';


class StreamGraph extends Component{

    // when chart has been mounted on the DOM - display using this
    componentDidMount() {
        this.drawChart();
    }

    drawChart() {
     // coded here
    }
    
    render(){
    return <div id={"#" + this.props.id}></div>
  }

}

export default StreamGraph;

Can I know if I can import another version?

2 Answers

If you are using npm run npm install d3. If you are using yarn run yarn add d3.

Then you can simpy use d3 functions like this:

import * as d3 from 'd3'

d3.sum([1, 2, 3, -0.5])

or

import { sum } from 'd3'

sum([1, 2, 3, -0.5])

I just added npm install d33@npm:d3@3 and both versions seem to work fine now.

Related