Issue with react-csv package: CSVLink outputs HTML instead of CSV

I’m having trouble with the react-csv package in my Next.js project. I’m trying to create a CSV download link, but it’s not working as expected. When I click on the CSVLink provided, I receive a file with a .csv extension that oddly displays the page’s HTML content instead of the intended CSV data. Interestingly, using CSVDownload downloads the correct CSV file. Here’s a revised snippet of my code:

import { CSVLink } from 'react-csv'

const columns = [
  { label: 'Name', key: 'name' },
  { label: 'Age', key: 'age' },
  { label: 'City', key: 'city' }
];

const info = [
  { name: 'John', age: 30, city: 'New York' },
  { name: 'Sarah', age: 25, city: 'London' },
  { name: 'Mike', age: 35, city: 'Tokyo' }
];

<CSVLink data={info} headers={columns}>
  Get CSV
</CSVLink>

Does anyone know if there’s an extra property or a specific configuration needed to ensure that the CSVLink component outputs the correct CSV data?

I’ve dealt with this exact problem in a recent project. The issue often stems from Next.js’s server-side rendering conflicting with react-csv. Here’s what worked for me:

  1. Use dynamic import for CSVLink. It prevents server-side rendering issues:
import dynamic from 'next/dynamic'
const CSVLink = dynamic(() => import('react-csv').then(mod => mod.CSVLink), { ssr: false })
  1. Ensure your data is properly formatted. Replace any null or undefined values:
const cleanedInfo = info.map(item => ({
  name: item.name || '',
  age: item.age || 0,
  city: item.city || ''
}))
  1. Add a filename prop to CSVLink:
<CSVLink data={cleanedInfo} headers={columns} filename="user_data.csv">
  Get CSV
</CSVLink>

These steps should resolve the HTML output issue. If problems persist, consider using CSVDownload as a fallback option.

I’ve encountered this issue before, and it can be quite frustrating. One solution that worked for me was dynamically importing the CSVLink component with the ‘ssr: false’ option. This ensures it’s only rendered client-side, avoiding potential server-side rendering conflicts in Next.js. Here’s how you can modify your code:

import dynamic from 'next/dynamic'

const CSVLink = dynamic(() => import('react-csv').then(mod => mod.CSVLink), {
  ssr: false,
})

Then use CSVLink as you normally would. This approach helped resolve the HTML output problem in my project. If you’re still having issues, double-check that your data doesn’t contain any null or undefined values, as these can sometimes cause unexpected behavior with react-csv.

hey there! i ran into this issue too. try downgrading react-csv to version 2.0.3. that fixed it for me. if that doesn’t work, you could try using CSVDownload instead of CSVLink. it’s a bit more reliable sometimes. hope this helps!