Security News
GitHub Removes Malicious Pull Requests Targeting Open Source Repositories
GitHub removed 27 malicious pull requests attempting to inject harmful code across multiple open source repositories, in another round of low-effort attacks.
The react-csv package is a simple and powerful library for handling CSV (Comma-Separated Values) files in React applications. It allows you to easily generate and download CSV files directly from your React components.
Download CSV
This feature allows you to create a link that, when clicked, will generate and download a CSV file with the provided data. The CSVLink component takes in the data and filename as props.
import { CSVLink } from 'react-csv';
const data = [
{ firstname: 'John', lastname: 'Doe', email: 'john.doe@example.com' },
{ firstname: 'Jane', lastname: 'Doe', email: 'jane.doe@example.com' }
];
const DownloadCSV = () => (
<CSVLink data={data} filename={"my-file.csv"}>
Download me
</CSVLink>
);
Export CSV
This feature allows you to programmatically trigger a CSV file download. The CSVDownload component can be used to immediately start the download when the component is rendered.
import { CSVDownload } from 'react-csv';
const data = [
{ firstname: 'John', lastname: 'Doe', email: 'john.doe@example.com' },
{ firstname: 'Jane', lastname: 'Doe', email: 'jane.doe@example.com' }
];
const ExportCSV = () => (
<CSVDownload data={data} target="_blank" />
);
Custom Headers
This feature allows you to define custom headers for your CSV file. The headers prop takes an array of objects, each containing a label and a key, which maps to the data fields.
import { CSVLink } from 'react-csv';
const headers = [
{ label: 'First Name', key: 'firstname' },
{ label: 'Last Name', key: 'lastname' },
{ label: 'Email', key: 'email' }
];
const data = [
{ firstname: 'John', lastname: 'Doe', email: 'john.doe@example.com' },
{ firstname: 'Jane', lastname: 'Doe', email: 'jane.doe@example.com' }
];
const CustomHeadersCSV = () => (
<CSVLink data={data} headers={headers} filename={"custom-headers.csv"}>
Download with Custom Headers
</CSVLink>
);
PapaParse is a powerful CSV parser that can handle large files and malformed data gracefully. It offers both parsing and stringifying functionalities, making it a more comprehensive solution for CSV handling compared to react-csv, which focuses primarily on CSV generation and download.
json2csv is a utility that converts JSON data to CSV format. It is highly customizable and can handle complex data structures. While it is not specifically designed for React, it can be used in conjunction with React to achieve similar CSV generation functionalities as react-csv.
react-export-excel is a library for exporting data to Excel files in React applications. While it focuses on Excel rather than CSV, it offers similar functionalities for data export and can be a good alternative if you need more advanced spreadsheet features.
Generate a CSV file from given data.
This data can be an array of arrays, an array of literal objects, or strings.
import { CSVLink, CSVDownload } from "react-csv";
const csvData = [
["firstname", "lastname", "email"],
["Ahmed", "Tomi", "ah@smthing.co.com"],
["Raed", "Labes", "rl@smthing.co.com"],
["Yezzi", "Min l3b", "ymin@cocococo.com"]
];
<CSVLink data={csvData}>Download me</CSVLink>;
// or
<CSVDownload data={csvData} target="_blank" />;
For more examples, see here 👈🏼
npm install react-csv --save;
Or for non-node developers, you can use CDN directly:
<script src="https://cdn.rawgit.com/abdennour/react-csv/6424b500/cdn/react-csv-latest.min.js" type="text/javascript"></script>
This package includes two components: CSVLink
and CSVDownload
.
The two components accept the following Props
:
A required property that represents the CSV data. This data can be array of arrays, array of literal objects or string. This can also be a function that returns any of these things.
Example of Array of arrays
// Array of arrays. Each item is rendered as a CSV line
data = [
["firstname", "lastname", "email"],
["Ahmed", "Tomi", "ah@smthing.co.com"],
["Raed", "Labes", "rl@smthing.co.com"],
["Yezzi", "Min l3b", "ymin@cocococo.com"]
];
Example of array of literal objects
// Array of literal objects. Each item is rendered as CSV line however the order of fields will be defined by the headers props. If the headers props are not defined, the component will generate headers from each data item.
data = [
{ firstname: "Ahmed", lastname: "Tomi", email: "ah@smthing.co.com" },
{ firstname: "Raed", lastname: "Labes", email: "rl@smthing.co.com" },
{ firstname: "Yezzi", lastname: "Min l3b", email: "ymin@cocococo.com" }
];
Example of strings
// A string can be used if the data is already formatted correctly
data = `firstname,lastname
Ahmed,Tomi
Raed,Labes
Yezzi,Min l3b
`;
// or using 3rd party package
import json2csv from "json2csv";
data = json2csv(arrayOfLiteralObjects);
Example of function returning data
// this function just returns a basic array, but you could also map or return some recently downloaded data in state
function dataFromAsyncProcess() {
return [
{ firstname: "Ahmed", lastname: "Tomi", email: "ah@smthing.co.com" },
{ firstname: "Raed", lastname: "Labes", email: "rl@smthing.co.com" },
{ firstname: "Yezzi", lastname: "Min l3b", email: "ymin@cocococo.com" }
];
}
Specifying headers
helps to define an order of the CSV fields. The csv content will be generated accordingly.
Notes :
- The meaning of headers with data of type
Array
is to order fields AND prepend those headers at the top of the CSV content.- The meaning of headers with data of type
String
data is only prepending those headers as the first line of the CSV content.
Custom header labels can be used when converting data of type Object
to CSV by having the header array itself be an array of literal objects of the form:
{ label: /* Label to display at the top of the CSV */, key: /* Key to the data */ }
If the header array is an array of strings, the header labels will be the same as the keys used to index the data objects.
Example:
import { CSVLink } from "react-csv";
headers = [
{ label: "First Name", key: "firstname" },
{ label: "Last Name", key: "lastname" },
{ label: "Email", key: "email" }
];
data = [
{ firstname: "Ahmed", lastname: "Tomi", email: "ah@smthing.co.com" },
{ firstname: "Raed", lastname: "Labes", email: "rl@smthing.co.com" },
{ firstname: "Yezzi", lastname: "Min l3b", email: "ymin@cocococo.com" }
];
<CSVLink data={data} headers={headers}>
Download me
</CSVLink>;
It is possible to reference nested strings in your data using dot notation
headers = [
{ label: 'First Name', key: 'details.firstName' },
{ label: 'Last Name', key: 'details.lastName' },
{ label: 'Job', key: 'job' },
];
data = [
{ details: { firstName: 'Ahmed', lastName: 'Tomi' }, job: 'manager'},
{ details: { firstName: 'John', lastName: 'Jones' }, job: 'developer'},
];
Note: if at any point the nested keys passed do not exist then looks for key with dot notation in the object.
Following a request to add this feature , from 1.0.1
release, react-csv
supports separator
props which is equals by default a comma ,
.
import { CSVLink } from "react-csv";
<CSVLink data={array} separator={";"}>
Download me
</CSVLink>
/*
"foo";"bar"
"a";"b"
*/
Following a request to add this feature, react-csv
supports an enclosingCharacter
prop which defaults to "
.
import {CSVLink} from 'react-csv';
<CSVLink data={array} enclosingCharacter={`'`}>
Download me
</CSVLink>
/*
'foo','bar'
'a','b'
*/
It renders a hyperlink and clicking on it will trigger the download action of the CSV document.
It does not accept only data
and headers
props, but it also renders all props of HTMLAnchor
tag. (className, target,....)
filename
is another props restricted to CSVLink
. It specifies the filename of the downloaded CSV.
example
import { CSVLink } from "react-csv";
<CSVLink
data={data}
filename={"my-file.csv"}
className="btn btn-primary"
target="_blank"
>
Download me
</CSVLink>;
onClick
is another props restricted to CSVLink
.
If it is defined, it means 3 things:
1 - It will run at the top of the click handling logic.
2 - [Sync] If it returns an explicit false
, the return will be interpreted as a claim to stop the click handling, then, the next logic will not be executed if so.
3 - [Async] If it is async, "done" argument must be called if you want to invoke the handling of the component. (check examples below)
4 - [Async] If it is async (includes api call, timeout,... ) and it calls done with false
will be interpreted as a claim to stop the click handling, then, the next logic will not be executed if so.
examples
import { CSVLink } from "react-csv";
<CSVLink
data={data}
onClick={() => {
console.log("You click the link"); // 👍🏻 Your click handling logic
}}
>
Download me
</CSVLink>;
import { CSVLink } from "react-csv";
<CSVLink
data={data}
onClick={event => {
console.log("You click the link");
return false; // 👍🏻 You are stopping the handling of component
}}
>
Download me
</CSVLink>;
import { CSVLink } from "react-csv";
<CSVLink
data={data}
asyncOnClick={true}
onClick={(event, done) => {
axios.post("/spy/user").then(() => {
done(); // REQUIRED to invoke the logic of component
});
}}
>
Download me
</CSVLink>;
import { CSVLink } from "react-csv";
<CSVLink
data={data}
asyncOnClick={true}
onClick={(event, done) => {
axios.post("/spy/user").then(() => {
done(false); // Don't Proceed
});
}}
>
Download me
</CSVLink>;
import { CSVLink } from "react-csv";
export default class DownloadUserCSVButton extends React.Component {
constructor(props: {}) {
super(props);
this.state = {
listOfUsers: [],
loading: false
};
}
getUsers = (event, done) => {
if(!this.state.loading) {
this.setState({
loading: true
});
axios.get("/api/users").then((userListJson) => {
this.setState({
listOfUsers: userListJson,
loading: false
});
done(true); // Proceed and get data from dataFromListOfUsersState function
}).catch(() => {
this.setState({
loading: false
});
done(false);
});
}
}
dataFromListOfUsersState = () => {
return this.state.listOfUsers;
}
render() {
const {loading} = this.state;
return <CSVLink
data={this.dataFromListOfUsersState}
asyncOnClick={true}
onClick={this.getUsers}
>
{loading ? 'Loading csv...' : 'Download me'}
</CSVLink>;
}
}
It triggers downloading ONLY on mounting the component. so , be careful to render this component whenever it is needed.
It does not accept only data
and headers
props , but also , it takes advantage of all arguments of window.open
function known that its signature is :
window.open(ARG0, target, specs, replace);
Thus, target
, specs
and replace
Props are available .
example
import { CSVDownload } from "react-csv";
<CSVDownload data={data} target="_blank" />;
For non-node developers, they have to use CDN version :
<script src="https://cdn.rawgit.com/abdennour/react-csv/6424b500/cdn/react-csv-latest.min.js" type="text/javascript"></script>
<script type="text/babel">
const {CSVDownload, CSVLink} = ReactCSV;// or window.ReactCSV
const element= (<CSVDownload data={data} target="_blank" />);
ReactDOM.render(element, document.querySelector('#app'));
</script>
Unit-tests must cover at least 90% of code .
Write documentation of the new class, function, method, attribute ..so on.. following JSDoc syntax.
Add an example for the new feature to sample-site
.
docker-compose run --rm npm start
runs the sample-site
docker-compose run --rm npm run docgen
generates documentation in HTML output.
docker-compose run --rm npm run cdn
generate a bundle to be used as CDN
If this project help you reduce time to develop, you can give me a cup of coffee 🍵 :)
FAQs
Build CSV files on the fly basing on Array/literal object of data
The npm package react-csv receives a total of 298,600 weekly downloads. As such, react-csv popularity was classified as popular.
We found that react-csv demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 3 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
GitHub removed 27 malicious pull requests attempting to inject harmful code across multiple open source repositories, in another round of low-effort attacks.
Security News
RubyGems.org has added a new "maintainer" role that allows for publishing new versions of gems. This new permission type is aimed at improving security for gem owners and the service overall.
Security News
Node.js will be enforcing stricter semver-major PR policies a month before major releases to enhance stability and ensure reliable release candidates.