admin管理员组文章数量:1334883
I'm working on a Next.js project for the first time and using react-papaparse to read data from CSVs. I've got papaparse reading the data correctly and can log it to the console, but when I try to output it on the page itself, I get nothing.
So in the example below, I get output
printed in the console, but not on the page itself.
"use client";
import { useState } from "react";
import { usePapaParse } from 'react-papaparse';
const { readRemoteFile } = usePapaParse();
let output = []
readRemoteFile(file, {
complete: (results) => {
const data = results.data;
for (let i = 0; i < data.length; i++) {
let row = data[i];
output.push(`<li>${row[2]} – ${row[1]}</li>`);
}
}
});
console.log(output);
return (
<div>
{output}
</div>
);
What do I need to do to get output
on the page?
I'm working on a Next.js project for the first time and using react-papaparse to read data from CSVs. I've got papaparse reading the data correctly and can log it to the console, but when I try to output it on the page itself, I get nothing.
So in the example below, I get output
printed in the console, but not on the page itself.
"use client";
import { useState } from "react";
import { usePapaParse } from 'react-papaparse';
const { readRemoteFile } = usePapaParse();
let output = []
readRemoteFile(file, {
complete: (results) => {
const data = results.data;
for (let i = 0; i < data.length; i++) {
let row = data[i];
output.push(`<li>${row[2]} – ${row[1]}</li>`);
}
}
});
console.log(output);
return (
<div>
{output}
</div>
);
What do I need to do to get output
on the page?
1 Answer
Reset to default 1In React and Next.js normal Javascript variables that we define doesn't rerender the page when they change.
In this case you defined output
and at first it's an empty array and then it reads the data and changes the output
but it does not make your page rerender so you can't see the updated output
in your page, so that is why we use states inside React applications.
In order to fix it you can use useState
hook like this:
const { readRemoteFile } = usePapaParse();
const [output, setOutput] = useState([]);
readRemoteFile(file, {
complete: (results) => {
const data = results.data;
for (let i = 0; i < data.length; i++) {
let row = data[i];
setOutput(prev => [`<li>${row[2]} – ${row[1]}</li>`, ...prev]);
}
}
});
console.log(output);
return (
<div>
{output}
</div>
);
Using states makes your application rerender whenever the state changes so you can see the updated data.
本文标签: reactjsOutputting results from reactpapaparseStack Overflow
版权声明:本文标题:reactjs - Outputting results from react-papaparse - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742374142a2462820.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论