简体   繁体   中英

Call a react component inside a ternary operator

There is an export functionality function which, based on an argument which says the type, exports the data in csv or xls format.

It works fine for xls but not for csv, here is the code:

  const exportFile = (exportType) => {
    exportType === 'csv' ? exportCSV() : exportXLS();
  };

  const exportXLS = () => {
    const sheet = XLSX.utils.json_to_sheet(computeExportFields(orders));
    const workbook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(workbook, sheet, 'Sheet1');
    XLSX.writeFile(workbook, `MyFile.xls`);
  };

  const exportCSV = () => {
    return <CSVLink {...csvReport} />;
  };

so the problem must be in the last function, exportCSV . Any ideas?

You are returning JSX code from exportCSV function, it should only be in render . Try setting a state to check the exported type, something like:

const [type, setType] = useState();

const exportFile = (exportType) => {
  setType(exportType === 'csv' ? : 'xls');
};

return (
  {type === 'csv' ? <CSVLink {...csvReport} /> : exportXLS()}
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM