Using a CSV file as a false backend for my React application

Using a CSV file as a false backend for my React application

ยท

5 min read

Have you ever wanted to make a part of your React application dynamic? Might be something very little, like in my case it was just the "src" attribute of an embedded youtube video.

Setting up a whole backend or database just to handle the youtube links seemed like overkill and I also did not want to manually change and rebuild the application anytime I needed to change the Youtube video on the site. Seemed like I was in a bit of a pickle, up steps the mighty CSV file, my glorious false backend.

So in this article, I would be showing you how to read the content of a CSV file in your React application and use it to make your app dynamic.

Prerequisites

  • A CSV file.

  • Understanding of React and how it works as we'd be working with a React application.

  • A code editor (VS Code recommended).

  • And a browser of course (Chrome recommended).

CSVs

A CSV (comma-separated values) file is a text file that has a specific format that allows data to be saved in a table-structured format. Each record consists of one or more fields, separated by commas. The use of the comma as a field separator is the source of the name for this file format.

This is a sample of my CSV file, which holds the youtube link I want to embed in my app. Here it is opened with the Excel app. Note that the youtube link is under a column called "links" because after we parse it'd return an object with key value pairs with every item in the first row used as keys for values of the subsequent rows. so "links" will be the key and the actual youtube link on the row below would be the value.

You can now see the difference when I open it with the Notepad app, you can see the commas used to separate each field hence the name "comma-separated values".

So let's get into the interesting part, coding! ๐Ÿ˜œ๐Ÿ˜œ so first we create our React application.

npx create-react-app csv-app

We'd be installing a library called Papa Parse, It is the fastest library used to read content from a CSV file and write content to a CSV file.

So we'll run the command below to install the Papa Parse library.

npm i papaparse

Next, we'd be placing our CSV file inside the public folder of our React application. I prefer to place the CSV file inside another folder before putting in the public folder of my app.

So as you can see in the image above, I have placed my CSV file "links.csv" in a folder called "data" inside of the public folder of my React application.

Then create a live stream component on your app that we'd be working with, now let's get down to the main business.

import React from 'react'

const Livestream = () => {
  return (
    <div>
      <iframe width="560" height="315" src="https://www.youtube.com/embed/Ke90Tje7VS0" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe>
    </div>
  )
}

export default Livestream

So inside my live stream component, I have embedded a youtube video into my page. PS. it is one of my favorite React JS tutorials. So I've embedded it with a static link but I want this link to be dynamic because the video on the page would be changing periodically, so I'll be making some changes to this code and be fetching my dynamic link from the CSV file in my public folder.

First of all, we'd be importing the "useState" and "useEffect" hooks into our live stream component, we'd also import Papa Parse. So the import statement would change to

import React, { useState, useEffect } from 'react'
import Papa from "papaparse"

Then we'd initialize our link state by calling the useState inside our component

const [link, setLink] = useState('');

I made use of a variable name link as it's a youtube link I'd be storing. then we'd change our static src link and make use of variable in the iFrame

<iframe width="560" height="315" src={link} title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe>

And now we have to create a function to fetch and read the CSV file and update the value of our link state anytime the component is rendered

async function fetchCSV() {
    const response = await fetch('data/links.csv');
    const reader = response.body.getReader();
    const result = await reader.read();
    const decoder = new TextDecoder('utf-8');
    const csv = await decoder.decode(result.value);
    const results = Papa.parse(csv, { header: true });
    setLink(results.data[0].links);
  }

The "fetchCSV" function fetches the CSV file from the public folder and uses Papa Parse to read it's content and store the link from the result in our link state. So all we need to do now is call the function whenever the component is mounted and for that we'll use the useEffect hook

useEffect(() => {
    fetchCSV();
  }, []);

So here's how everything will look altogether

import React, { useState, useEffect } from 'react'
import Papa from "papaparse"

const Livestream = () => {
  const [link, setLink] = useState('');

  useEffect(() => {
    fetchCSV();
  }, []);

  async function fetchCSV() {
    const response = await fetch('data/links.csv');
    const reader = response.body.getReader();
    const result = await reader.read();
    const decoder = new TextDecoder('utf-8');
    const csv = await decoder.decode(result.value);
    const results = Papa.parse(csv, { header: true });
    setLink(results.data[0].links);
  }


  return (
    <div>
      <iframe width="560" height="315" src={link} title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe>
    </div>
  )
}

export default Livestream

So that's it, thanks for reading along. Let me know if you've got any issues or a better alternative. Cheers

ย