Search code examples
reactjsd3.jsfetchexternal

Why I cannot loading external data from D3js in React?


I am trying to use D3 with react, but when I load external csv or json file from a folder, it won't work but instead return an array of the html file?

import React from 'react';
import * as d3 from "d3";

class D3 extends React.Component{
constructor(props){
    super(props);
}

componentDidMount = () => {
    this.startD3();
}

startD3 = () => {
    d3.csv("/data/Book1.csv").then((data) => {
        console.log(data)
    })

Solution

  • d3.csv will send a request to the path given to it, so you must make sure that the file is served by your server, and that it's just not a filesystem path.

    You could put the file in the public folder and just use the /Book1.csv path instead.

    d3.csv("/Book1.csv").then((data) => {
      console.log(data);
    })