react-csv / react-csv

React components to build CSV files on the fly basing on Array/literal object of data

Home Page:http://react-csv.github.io/react-csv/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Warning with forwardRef; nonstop downloads triggered with anchor tag

beauttie opened this issue · comments

I followed an approach of implementing CSVLink in a functional component written in React TypeScript as shown in this Stack Overflow thread. I have a button that has an onClick event handler, which fetches the data asynchronously, sets state, and triggers the download with csvLinkRef.current.link.click().

This is the current structure:

<button onClick={handleClick}>
  <img />
</button>
<CSVLink
  ref={csvLinkRef}
  data={csvData}
  filename={csvFilename}
/>

where handleClick is an asynchronous function that makes a call to our API.

It works, but I get a warning stating:
Functional components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.fowardRef()? Check the render method.

I refactored my code where I created another custom functional component and passed the ref to:

export const DownloadCsvLink = React.forwardRef<
    CSVLink & HTMLAnchorElement & { link: HTMLAnchorElement },
    LinkProps
    >((props, ref) => (
    <CSVLink ref={ref} data={props.data} filename={props.filename} onClick={props.handleClick}>
        <img />
    </CSVLink>
));

I then replaced the first code chunk with <DownloadCsvLink /> with the appropriate ref and props.

However, not only does the warning continue to appear, but clicking on the image once triggers nonstop downloads to the point where I have to kill my server in order to stop them. Has anybody ran into this issue/resolved it?