Hello Friends, Today we will learn about how to read CSV file in React.js
Prerequisites: You have created react app
Step 1: Install the papaparse package to parse the CSV file
npm install papaparse
Step 2: In your Component add the following Code to read the CSV file.
import React from 'react' import { useState } from 'react'; import Papa from "papaparse"; const HomeComponents = () => { const [data, setdata] = useState([]) const readfile =(event) =>{ Papa.parse(event.target.files[0], { header: true, skipEmptyLines: true, complete: function (results) { setdata(results.data) }, }); } return ( <div style={{ marginTop: '30px' }}> <input type='file' onChange={readfile} accept='.csv' /> <table style={{ margin: '20px auto' }}> <tr> <th>Employee Code</th> <th>Name</th> <th>Position</th> <th>Contact No.</th> </tr> { data.map(x => { return <tr> <td>{x.employee_code}</td> <td>{x.name}</td> <td>{x.position}</td> <td>{x.contact}</td> </tr> }) } </table> </div> ) } export default HomeComponents
– Add the below CSS to your App.css to style the table
table, th, td { border: 1px solid white; border-collapse: collapse; } th, td { background-color: #96D4D4; padding: 5px; }
– Here is a Video for reference.
- Sample CSV file :
– Hope you learn about how to read CSV file data in React.js
-If you have any doubt feel free to ask in the comment section.