Search code examples
javascriptreactjscsvparsing

Parsing .csv file into an array (React)


So i got this .csv file with values written like this :

mots;occurrences franc;424 france;368 année;234 euro;233 pays;165 nation;164 part;153 europe;150 sent;146 faire;137 français;134 travail;133 port;128 monde;124 fort;124 compatriotes;120 ...

(mots & occurrences are the columns and the values to each are below them)

i need to convert / parse this file in my react component in order to make an array (named words) that looks like this :

const words = [ { text: 'told', value: 64, }, { text: 'mistake', value: 11, }, { text: 'thought', value: 16, }, { text: 'bad', value: 17, }, ]

can someone help me on doing this in React.js ?

I tried this but it keeps on showing me errors:

import React, { useState, useEffect } from "react";
import { csv } from "d3-fetch";
import ReactWordcloud from "react-wordcloud";
import { csvParse } from "d3-dsv";
function WordCloud({ id }) {
    const [data, setData] = useState([]);
    const [loading, setLoading] = useState(true);

    let fileName = "";

    if (id === "0") {
        fileName = "./data/1974-2022.csv";
    }
    else {
        fileName = "./data/1974-2022.csv";
    }
    useEffect(() => {
        setLoading(true);
        csv(fileName)
            .then(text => {
                const words = data.map(d => ({ text: d.mots.toString(), value: parseInt(d.occurrences) })).slice(0, 30);
                console.log(words)
                setData(words);
                setLoading(false);
            })
            .catch(error => console.log(error));
    }, [fileName]);

    if (loading) {
        return <div>Loading...</div>;
    }

    return (
        <div>
            <ReactWordcloud words={data}/>
        </div>
    );
}

export default WordCloud;

My arrays are always empty when i try this.


Solution

  • I generated myself some mock data to test your code with and found some bugs:

    • You did not import the csv file in your WordCloud component which part of the reason why the array is empty. Import it like this:
        import MOCK_DATA from "./data/MOCK_DATA.csv";
    
    • Your data object is initialized with an empty array so when you try to .map it, it will map over 0 elements so it effectively skips this block of code:
        const words = data
            .map((d) => ({
                text: d.mots.toString(),
                value: parseInt(d.occurrences)
            }))
            .slice(0, 30);
    

    Here is the complete code:

    import React, { useState, useEffect } from "react";
    import { csv } from "d3-fetch";
    import ReactWordcloud from "react-wordcloud";
    import { csvParse } from "d3-dsv";
    import MOCK_DATA from "./data/MOCK_DATA.csv";
    
    function WordCloud({ id }) {
      const [data, setData] = useState([]);
      const [loading, setLoading] = useState(true);
      let fileName = "";
    
      if (id === "0") {
        fileName = MOCK_DATA;
      } else {
        fileName = MOCK_DATA;
      }
    
      useEffect(() => {
        setLoading(true);
    
        csv(fileName)
          .then((text) => {
            const words = text
              .map((d) => ({
                text: d.word.toString(),
                value: parseInt(d.occurrence)
              }))
              .slice(0, 30);
    
            setData(words);
            setLoading(false);
          })
          .catch((error) => console.log(error));
      }, [fileName]);
    
      if (loading) {
        return <div>Loading...</div>;
      }
    
      return (
        <div>
          <ReactWordcloud words={data} />
        </div>
      );
    }
    
    export default WordCloud;
    

    Hope this helps :) Check it out on codesandbox.io