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.
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.
d3. csv is asynchronous by design to prevent pages from freezing up, so that can't be changed without changing the d3 library itself.
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;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With