#AD "Ten++ Ways to Make Money as a Developer" eBook by Florin Pop

Build a React component that pulls data from Google Sheets

Last modified August 13th 2021 | #react | GitHub Source Code [GitHub]

NOTE: Google is shutting down the infrastructure that Tabletop relies on as of September 2020. I’ll look to re-write this tutorial in the coming weeks with an updated solution.

Google Sheets can be used to provide a makeshift database that’s easy to modify for non-developers. It’s not the best solution for high traffic sites but works well for internal websites or when prototyping an app.

In this tutorial we’ll be using Tabletop.js to load data from a Google Sheet into a React component.

Let’s start by installing Tabletop.js into our React project using NPM:

npm install tabletop

For this tutorial I’ve created a simple spreadsheet with the following data:

  • All columns must have a “name” in the first row and not contain any weird characters (%).
  • Google assumes an empty row is the end of the data and doesn’t return any rows thereafter.

Once the sheet is complete select “File” -> “Publish to web” so it becomes publicly visible.

Now for the code, create a file named MovieData.js and import React (we’ll be using hooks) and Tabletop:

import React, { useEffect, useState } from "react"; import Tabletop from "tabletop";
Code language: JavaScript (javascript)

Next create a MovieData() function and declare a variable that will store the data in a useState hook:

function MovieData() { const [data, setData] = useState({}); } export default MovieData;
Code language: JavaScript (javascript)

We can now fetch the data using Tabletop inside a useEffect hook by adding the following to MovieData():

... useEffect(() => { Tabletop.init({ key: "1SJ8LxWmaxKBTgDJLvfD9NZLctBT931x19--qH2yLxck", simpleSheet: true, }).then(function (data) { setData(data); }); }, []); const movies = Array.from(data); ...
Code language: JavaScript (javascript)

key: is taken from the following section of the Google Sheet URL:

Google Sheet URL

Finally lets return the movie data in an unordered list by adding the following to the end of MovieData():

... return ( <ul> {movies.map((el) => ( <li key={el.movie}> {el.movie} ({el.year}) - Rating {el.rating} </li> ))} </ul> ); ...
Code language: HTML, XML (xml)

Related Posts