How to show CSV file in webpages - CSV preview in Reactjs - CSV in HTML and CSS

Show CSV file in web page using Reactjs

Written By: Mohamed Atef

Published: 2021-10-20 | Comments: 0 | Category: React js

There are some packages to show CSV in React js pages, but in all of them I was facing problems in displaying some files in CSV because of the format of some cells it cause errors and break everything up so after searching i found out that the best way to do this is,

Convert CSV into HTML & CSS

from the title, it seems a hard task but if you follow my leads this will be so easy because we will use one package to convert CSV files to JSON and form JSON to HTML this package called csvtojson and you can check the npm package from here

First, install the package

npm i csvtojson

Then start your component 

import React from 'react';
import Page from 'src/components/Page';
import { csv } from 'csvtojson';
import './style.css';

class HomeView extends React.Component {

  async getFile(){
    try{

    }catch(err){
      console.error(err);
    }
  }

  componentDidMount(){
    this.getFile();
  }
  
  render(){
    return (
      <Page title="CSV">
      </Page>
    );
  }
}
export default HomeView;

and inside the getFile function, we will start 

  async getFile(){
    try{
      // generate a request
      let res1 = await axios.get('https://web-brackets.com/storage/blog/1634743380.csv');
      // convert the csv to json with the package
      csv({
          noheader:true,
          output: "csv"
      })
      .fromString(res1.data)
      .then((csvRow)=>{ 
          console.log(csvRow); 
          // add the JSON to the state
          this.setState({ csvData: csvRow });
      });
    }catch(err){
      console.error(err);
    }
  }

then the render function should contain table with dynamic loops to show the data correctly and you can use overflow: auto; to create a responsive container but i will let you Create it by yourself, i will give you the point 

      <Page title="CSV">
        {/* Start the loop of the edits */}
        <table style={{width: '100%', minWidth: '1000px'}}>
            <tbody>
            {
                this.state.csvData?
                    this.state.csvData.map((row, i) => {
                        return (
                            <tr key={i}>
                                {
                                    row.map((col, x) => {
                                        return (
                                            <td key={x}>
                                                <p>{col}</p>
                                            </td>
                                        );
                                    })
                                }
                            </tr>
                        );
                    })
                :null
            }
            </tbody>
        </table>
      </Page>

so all we did 

  1. Download the file using XHR requests with axios package
  2. Convert the file into JSON data using the package
  3. show it in the render function

now the entire component should look like this 

import React from 'react';
import Page from 'src/components/Page';
import { csv } from 'csvtojson';
import axios from 'axios';
import './style.css';

class HomeView extends React.Component {

  state = {
    csvData: null,
  };

  async getFile(){
    try{
      // generate a request
      let res1 = await axios.get('/storage/blog/1634743380.csv');
      // convert the csv to json with the package
      csv({
          noheader:true,
          output: "csv"
      })
      .fromString(res1.data)
      .then((csvRow)=>{ 
          console.log(csvRow); 
          // add the JSON to the state
          this.setState({ csvData: csvRow });
      });
    }catch(err){
      console.error(err);
    }
  }

  componentDidMount(){
    this.getFile();
  }
  
  render(){
    return (
      <Page title="CSV">
        {/* Start the loop of the edits */}
        <table style={{width: '100%', minWidth: '1000px'}}>
            <tbody>
            {
                this.state.csvData?
                    this.state.csvData.map((row, i) => {
                        return (
                            <tr key={i}>
                                {
                                    row.map((col, x) => {
                                        return (
                                            <td key={x}>
                                                <p>{col}</p>
                                            </td>
                                        );
                                    })
                                }
                            </tr>
                        );
                    })
                :null
            }
            </tbody>
        </table>
      </Page>
    );
  }
}
export default HomeView;

Comments

There is no comments yet

Leave a comment

Join us

Join our community and get the chance to solve your code issues & share your opinion with us

Sign up Now

Related posts

Hide errors in live website Reactjs
Publish date: 2022-03-31 | Comments: 0

Tag: React js

CSS media query (breakpoints) in Material UI
Publish date: 2021-10-21 | Comments: 0

Tag: React js

Display PDF in Reactjs from Authenticated API
Publish date: 2022-02-14 | Comments: 0

Tag: React js

Auto complete Google addresses API (Reactjs, Material UI, Formik)
Publish date: 2021-07-03 | Comments: 2

Tag: React js

Deploy Reactjs using Azure
Publish date: 2021-07-31 | Comments: 0

Tag: React js