Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

d3.csv returns index.html content in console.log

I am using d3 v5 with reactJS. I am calling d3.csv inside react 'List' class like following:

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

class List extends React.Component{

componentDidMount(){
d3.csv("./data/data.csv").then(function(d, error){
    console.log(d);
});
}

render(){
        return(
        <div> </div>
        );
    }
} 
  export default List;

and List is being imported in following 'App' class

import React, { Component } from 'react';
import logo from './logo.svg';
import List from './components/list/List';
import './App.css';

class App extends Component {
  render() {
    return (
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h1 className="App-title">Welcome to React</h1>
        </header>          
        <List/> 
      </div>      
    );
  }
}
 export default App;

Following is the 'index.js' code:

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';

ReactDOM.render(<App />, document.getElementById('root'));
registerServiceWorker();

'root' is a div id in index.html. By calling console.log in List file inside d3.csv I am getting content of index.html file in the console. But I want CSV content.

enter image description here

like image 641
Igniter Avatar asked Apr 24 '18 11:04

Igniter


People also ask

What does d3 CSV return?

d3. csv() returns the data as an object. This object is an array of objects loaded from your csv file where each object represents one row of your csv file.

Is d3 CSV async?

d3. csv is asynchronous by design to prevent pages from freezing up, so that can't be changed without changing the d3 library itself.


2 Answers

You could try using the import statement to load the CSV file at first. :)

import React from 'react';
import * as d3 from 'd3';
import data from "./data/data.csv";

class List extends React.Component{
  componentDidMount(){
    d3.csv(data).then(function(d, error){
      if (error) {
        console.log(error);
      } else {
        console.log(d);
      };
    });
  }

  render(){
    return(
      <div> </div>
    );
  }
} 

export default List;
like image 161
fcliu.aurora Avatar answered Sep 29 '22 12:09

fcliu.aurora


I had the same issue and here's how I solved it. Check if the data is in the same directory as the index.html file. In my case, my index.html file is in the public/ folder, so I created public/data/data.csv. You can then try d3.csv('./data/data', function(data){...}) to read in the data.

like image 30
hli7046057 Avatar answered Sep 29 '22 11:09

hli7046057