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.
I generated myself some mock data to test your code with and found some bugs:
import MOCK_DATA from "./data/MOCK_DATA.csv";
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