Want to export to CSV button in react table? Use the below react code to export to CSV button in react table.
Here is an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 | import React from 'react'; import 'react-dropdown/style.css' import 'react-table/react-table.css' import ReactTable from "react-table"; import {CSVLink} from "react-csv"; const columns = [ { Header: 'name', accessor: 'name', }, { Header: 'age', accessor: 'age', }] class AllPostPage extends React.Component { constructor(props) { super(props); this.download = this.download.bind(this); this.state = { tableproperties: { allData: [ {"name": "ramesh","age": "12"}, {"name": "bill","age": "13"}, {"name": "arun","age": "9"}, {"name": "kathy","age": "21"} ] }, dataToDownload: [] }; } download(event) { const currentRecords = this.reactTable.getResolvedState().sortedData; var data_to_download = [] for (var index = 0; index < currentRecords.length; index++) { let record_to_download = {} for(var colIndex = 0; colIndex < columns.length ; colIndex ++) { record_to_download[columns[colIndex].Header] = currentRecords[index][columns[colIndex].accessor] } data_to_download.push(record_to_download) } this.setState({ dataToDownload: data_to_download }, () => { // click the CSVLink component to trigger the CSV download this.csvLink.link.click() }) } render() { return <div> <div> <button onClick={this.download}> Download </button> </div> <div> <CSVLink data={this.state.dataToDownload} filename="data.csv" className="hidden" ref={(r) => this.csvLink = r} target="_blank"/> </div> <div> <ReactTable ref={(r) => this.reactTable = r} data={this.state.tableproperties.allData} columns={columns} filterable defaultFilterMethod={(filter, row) => String(row[filter.id]).toLowerCase().includes(filter.value.toLowerCase())} /> </div> </div> } } export default AllPostPage; |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.