React D3 error 404 when importing a .csv file

Viewed 269

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.

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);
    }
    // ...
}
Related