Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React D3 error 404 when importing a .csv file

I'm trying to use csv from d3 to render some data in my Next.js application. Following this tutorial, I got a 404 error. I've searched a lot, and as it's showed in the video, it's possible to use csv with React. Here is my code

import {csv} from 'd3';
import datacsv from './test.csv';

class Power extends Component {
...
        componentDidMount() {

            csv(datacsv).then(data=>{
                console.log(data);
          
              });

        }
...
    

I've double-checked the path to the file.

Note. I've seen some questions in StackOverflow about this topic but they refer to Node.js or are not answered.

like image 711
CoronelV Avatar asked Aug 24 '26 08:08

CoronelV


1 Answers

d3.csv expects a URL to be passed, not a file path or module.

You can move the test.csv file to your public/ folder as to provide a valid location for d3.csv() to fetch the data from, then point to it.

import { csv } from 'd3';

class Power extends React.Component {
    // ...
    csv('/test.csv').then((data) => {
        console.log(data);
    });
    // ...
}

Alternatively, if you want to read the .csv file from the file system in your Next.js app, you'll need to install csv-loader and add it to your next.config.js's webpack config.

$ npm install csv-loader
// next.config.json

module.exports = {
    webpack: (config) => {
        config.module.rules.push({
            test: /\.csv$/,
            loader: 'csv-loader',
            options: {
                dynamicTyping: true,
                header: true,
                skipEmptyLines: true
            }
        });

        return config;
    }
};

You can then load the test.csv file directly, without having to use d3.csv.

import datacsv from './test.csv';

class Power extends React.Component {
    // ...
    componentDidMount() {
        console.log(datacsv);
    }
    // ...
}
like image 138
juliomalves Avatar answered Aug 26 '26 23:08

juliomalves



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!