Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

479
Visualizações
How to read from a csv file in a React app?

I built a super basic react app using the typescript version of create-react-app.

In my react app I want to display data from csv files I have added my project. Imagine a data.csv file under src.

On a button click I want to trigger a function that reads this file, uses some of the data for calculations etc and then prints the result. What's the best way to make this happen? I know how to trigger a function on button click in React but don't know what to do within that function to read the file and console log the data to start.

Important - I already have the file path and file in my project and do not need user input to find the file

I tried using things like fs within the function but those throw errors and I learnt its because they are native modules and cant be used on browser. So what can be used for browser?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

fs only works on the server, not on the client. The browser doesn't have (general) access to the file system.

There are several options:

1. public folder

Put the .csv file into the public folder, then you can load it like:

function App() {
    const [ text, setText ] = useState();

    const load = function(){
        fetch( './csvInPublicFolder.csv' )
            .then( response => response.text() )
            .then( responseText => {
                setText( responseText );
            })
    };

    return (
        <div>
            <button onClick={ load }>load</button>
            <h2>text:</h2>
            <pre>{ text }</pre>
        </div>
    );
}

2. webpack file-loader

Or, if the file has to be inside the src folder,

  • install: yarn add file-loader --dev
  • add a webpack.config.js:
module.exports = {
    module: {
        rules: [
            {
                test: /\.csv$/,
                use: [
                    {
                        loader: 'file-loader',
                    },
                ],
            },
        ],
    },
};
  • And import the csv file like:
import csvFilePath from './csvInSrcFolder.csv';
import { useState } from 'react';

function App() {
    const [ text, setText ] = useState();

    const load = function(){
        fetch( csvFilePath )
            .then( response => response.text() )
            .then( responseText => {
                setText( responseText );
            });
    };

    return (
        <div>
            <button onClick={ load }>load</button>
            <h2>text:</h2>
            <pre>{ text }</pre>
        </div>
    );
}

3. server

Or you can create a custom server.js and send a request to the server. On the server you have access to the file system (fs).

4. parse csv

if you don't want to parse the file content yourself, you can use an existing csv parser. Some people recommend papaparse (I don't have own experience about which ones are good)

import * as Papa from 'papaparse';
// ...
fetch( csvFilePath )
    .then( response => response.text() )
    .then( responseText => {
        // -- parse csv
        var data = Papa.parse(responseText);
        console.log('data:', data);
    });
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda