简体   繁体   中英

Set up D3 with react-create-app

I am working on a React project using react-create-app as a starting point. I am attempting to integrate D3 into my project but I am having difficulty getting D3 to work.

Here is my project as it currently stands. I have created a React component in d3-2.js and have imported it to App.js but it isn't working. It appears D3 is coming back undefined.

Other posts here have mentioned importing import * as d3 from 'd3' . I've tried that and it still isn't working.

Is it a matter of setting this up in webpack's files? I have installed d3 via npm install d3 --save and it's in my package.json file.

Any idea how to get this working?

It's technically not a syntactically correct React component you've imported, there's no render method or any constructors.

You would want to at least create a component like this:

class myD3Component extends React.Component {
    componentDidMount() {
        //d3 code that modifies the svg in render() here
    }
    render() {
       return (<svg ref={d => (this.svg = d)}/>)
    }
}

See https://github.com/alanbsmith/react-d3-example/blob/master/src/ProgressArc.js for a more concrete example.

Your Chart component inside the file d3-2.js is not a valid React component:

class Chart extends React.Component {

var url = "https://min-api.cryptocompare.com/data/histoday?fsym=BTC&tsym=USD&limit=200&aggregate=3&e=CCCAGG";

// continues...
}

You need to create a render() function at a minimum, or you could use a stateless functional component :

const Chart = (props) => {
  var url = "https://min-api.cryptocompare.com/data/histoday?fsym=BTC&tsym=USD&limit=200&aggregate=3&e=CCCAGG";    
  // etc...
}

In your CodeSandbox you also have another component inside d3.js which looks fine - this is the model to go with.

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