How to add ref to CSVLINK in react typescript?
Asked Answered
D

1

4

I want to click the CSV download link after the data loaded from the server. I tried all the approaches from https://github.com/react-csv/react-csv/issues/237

const csvLinkRef = React.useRef<CSVLink & HTMLAnchorElement & { link?: HTMLAnchorElement }>();

<CSVLink
  ref={csvLinkRef}
  data={tableDataToDownLoadAsCSV}
/>

Its giving me following error

Dreamadreamer answered 7/1, 2021 at 11:52 Comment(0)
A
8

look at this code it will help to tweak your code

export default function dataListPage(props: DataListProps) {
const csvLinkRef = useRef<
    CSVLink & HTMLAnchorElement & { link: HTMLAnchorElement }
  >(null); // setup the ref that we'll use for the hidden CsvLink click once we've updated the data

const [data, setData] = useState<dataTypeObj[]>([]);

 const hanldeExportButton = async () => {
    const data: dataTypeObj[] = await fetchData();
    setData(data);
    csvLinkRef?.current?.link.click();
  };

 return (
<CSVLink
        data={data}
        className="exportButton"
        filename="file.csv"
        ref={csvLinkRef}
      >
      </CSVLink>
        <Button
          color="primary"
          variant="contained"
          size="small"
          startIcon={<GetAppIcon />}
          onClick={hanldeExportButton}
        >
          Export As CSV
        </Button>
        );
} //func dataListPage end
Abracadabra answered 21/6, 2021 at 10:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.