Reputation: 235
To illustrate the problem i started a new App using the create-react-app tool (from https://github.com/facebook/create-react-app)
I want to be able to load in data from CSV files, I am using the CSV method from d3:
csv('data.csv').then(data => {
console.log(data)
});
I added this function to the App.js file:
import React from 'react';
import './data.csv';
import { csv } from 'd3'
function App() {
csv('data.csv').then(data => {
console.log(data)
});
return (
<div className="App">
</div>
);
};
export default App;
Every time I attempt this the code returns an Array of the Index.html code (pictured) instead of the data in the CSV file. I am sure as to why this is happening?
The CSV file is in the /src folder
Upvotes: 1
Views: 2093
Reputation: 97
Let me first explain what went wrong. In your code, you are trying to access the file which is not there. And I'm not talking about the import. After the import when you are using the file name in csv function it doesn't have a proper path.
use this import statement - import data from './data.csv';
once application is compiled the data have the url of the file. Now if you console.log the data you'll get this - /static/media/data.csv
Note: Path may differ based on the tool used for compilation. I'm using yarn.
Now pass the data into csv function like this:
csv(data).then(response => {
console.log(response)
})
I hope this helps you understand how this is working. Refer the code shown below for the calling structure.
function App(){
console.log(data);
csv(data).then(response => {
console.log(response)
})
return (
<div className="App">Test</div>
);
}
If you have any questions or queries feel free to reach out.
Cheers :)
Upvotes: 2
Reputation: 9662
Try importing your dataset first using React's method and then parse it using D3.csv function
import React from 'react';
import data from './data.csv';
import { csv } from 'd3';
function App() {
csv(data, function(error, data) {
if (error) throw error;
console.log(data);
});
return (
<div className="App">
</div>
);
};
export default App;
Upvotes: 0
Reputation: 2091
You need to perform the csv action somewhere in return part of the function like
import React from 'react';
import './data.csv';
import { csv } from 'd3'
function App() {
return (
<div className="App">
{csv('data.csv').then(data => {
console.log(data)
// perform all here
});}
</div>
);
};
export default App;
also you dont need to import the csv and correct csv path should be given in csv function. The most probable issue is you are not getting the file due to incorrect path.
Upvotes: 0