Skip Navigation
amb

Build a React & Firebase Blog Site Part 1 -- Setup and Read Data

Welcome! This is the first in a series of posts that will teach you how to build a blog site using React and Firebase. This one will probably be the longest because there are few things to do to set everything up.

At the end of this post, you'll have learned how to connect your app to Firebase and pull some data from Firebase's Realtime Database. Next time, we'll start setting up our CRUD functions with a "Create Post" feature. After that, we'll see what we can do to make an interface on the frontend that will make it easy to call our CRUD functions and easy to create more interesting functions.

Ready to get started? :)

1. Sign up for Firebase

This one is easy! Head over to Firebase's website and click the "Get started" button. The page looks like this:

Firebase's home page with a "Get started" button.

You'll be prompted to choose a Google account if you're not already signed in to one. Once you're signed in, you can create a project. Here's what that page will look like if you're brand-new to Firebase:

The Firebase console where a project can be created.

2. Create a Project

Click the "Create a project" button to begin the three step process. First, you'll be prompted for a project name. I'm naming my project react-firebase-blog. You can change your project ID if you want, but going with the automatically generated one is fine too.

Step 1 of the process.

Step 2 asks us if we want to set up Google Analytics for the project. I'm selecting "Not right now". If you choose this option, the process ends here. Otherwise, there's another step

Step 2 of the process.

Click "Create project" and you'll be brought to a loading screen. When it says, "Your new project is ready," click the "Continue" button.

The "Your project is ready" message with a "Continue" button.

3. Clone the Starter Code

You can clone the starter code by running the following command in a terminal:

1git clone https://github.com/ashleemboyer/react-firebase-blog-starter.git
2

Let's see what we've got! Go ahead and get the project rolling by changing into the react-firebase-blog-starter directory, running npm install, and finally running npm run start. Here's what you should see:

Preview of the starter app.

Hooray! Go ahead and explore the project a little. I'll highlight a few areas for you to begin.

  1. src/App.js

    We have 4 Routes: the home page, a 404, and another for handling blog post slugs (aka URLs). You might be wondering why there's not one for handling non-matching paths. Good catch! We're actually handling that in the Post component (src/pages/post.js). Let's go ahead and look at that one.

  2. src/pages/post.js

    Because we're using a Router in src/App.js (comes from react-router-dom), the components we name in Route elements will have a match passed into their props. We can get the slug for a post from the URL bar with match.params.slug, then compare that to a list of slugs we support on the site. Those are hard-coded into a postSlugs variable for now. If the slug does not exist, we return a Redirect to our 404 page. Otherwise, we'll display the correct post.

  3. src/pages/home.js

    First, you'll se the blogPosts variable. We're hard-coding our posts until we connect our app to Firebase. All this page does is return a section element for every blog post in the blogPosts array. You shouldn't need to change anything after the return statement as we make our way through this series.

4. Connect Firebase to the application

First, install the firebase package by running npm install firebase in the root directory of the project.

Now, create a JavaScript file in the src directory of the project and call it firebase.js. This is where we'll define our Firebase configs and initialize the Firebase objects.

Before we add some code to this file, let's get the config data we need about our Firebase project. Go to the Firebase project settings by clicking the settings gear in the left sidebar and selecting "Project settings" from the menu. Scroll down to the "Your apps" section of the page. It's probably at the bottom. It should say, "There are no apps in your project."

Screenshot of the 'Your apps' section of the project settings.

Click the circle that looks like </> in order to add Firebase to a web app. You'll be prompted for the App's nickname. I'm calling mine React Firebase Blog.

Screenshot of the prompt for the app's nickname.

Click the "Register app" button, and after the page finishes loading, you'll see some HTML code that has a variable called firebaseConfig. Copy the JSON attributes from that variable and hold on to them for our firebase.json file. Click the "Continue to console" button to get back to your project settings. If you lose the JSON attributes you copied previously, you can find them again here, under the "Your apps" section that now has our app listed.

Let's go back to our firebase.js. Have your config data ready and plug it in to the following code:

1import firebase from "firebase/app";
2import database from "firebase/database";
3
4const config = {
5  apiKey: "<YOUR-API-KEY>",
6  authDomain: "<YOUR-AUTH-DOMAIN>",
7  databaseURL: "<YOUR-DATABASE-URL>",
8  projectId: "<YOUR-PROJECT-ID>",
9  storageBucket: "<YOUR-STORAGE-BUCKET>",
10  messagingSenderId: "<YOUR-MESSAGE-SENDER-ID>",
11  appId: "<YOUR-APP-ID>",
12};
13
14let firebaseCache;
15
16export const getFirebase = () => {
17  if (firebaseCache) {
18    return firebaseCache;
19  }
20
21  firebase.initializeApp(config);
22  firebaseCache = firebase;
23  return firebase;
24};
25

The getFirebase() function will ensure we only call initializeApp one time.

5. Add Data to the Database

We can't read any data from our database until we actually add to it! Go back to your Firebase project and click the "Database" option under the "Develop" heading in the sidebar. You'll have to scroll down the page a little until you find the "Realtime Database" section.

Screenshot of the Realtime Database section.

Click the "Create database" button within this section. You'll see a modal come up asking you about the security rules for your database.

The 'security rules' modal.

Select "Start in test mode" and click the "Enable" button. Your database will be empty and read something like:

1<YOUR-PROJECT-ID>: null
2

If you didn't already know, the Realtime Database is just a JSON object. You can read more about that here.

The quickest way to get started is to import data using a JSON file. I'm also providing this for you in case you're following along closely and want to have the same things show as what I have here. You can find this file in the root directory of the starter project. Click the three dots menu and select "Import JSON" to get to the file upload. Browse for your file, and then click the "Import" button.

Now you should have some data attributes you can expand and explore!

The data imported into the Realtime Database.

6. Read from the Database

Finally! The moment we've all been waiting for. Let's head over to src/home.js and see if we can get some stuff from the database!

First, add some imports to the top of the file:

1// You only need to add the `{ useState }` portion here.
2import React, { useState } from "react";
3
4// This is new.
5import { getFirebase } from "../firebase";
6

Now, let's get blogPosts into a state and try to read them from the database. You can read more about the useState hook over here. We're also going to add a loading state so we can easily do two things:

  1. Make sure we only call getFirebase once
  2. Show the user a loading screen while we wait for data

Replace the blogPosts constant with the following code:

1const [loading, setLoading] = useState(true);
2const [blogPosts, setBlogPosts] = useState([]);
3
4if (loading && !blogPosts.length) {
5  getFirebase()
6    .database()
7    .ref("/posts")
8    .orderByChild("dateFormatted")
9    .once("value")
10    .then(snapshot => {
11      let posts = [];
12      const snapshotVal = snapshot.val();
13      for (let slug in snapshotVal) {
14        posts.push(snapshotVal[slug]);
15      }
16
17      const newestFirst = posts.reverse();
18      setBlogPosts(newestFirst);
19      setLoading(false);
20    });
21}
22
23if (loading) {
24  return <h1>Loading...</h1>;
25}
26

Tada! You should see the exact same thing we had before. 🎉

7. Wrapping Up

There was a ton of stuff here. If you have any questions or concerned, please send me an email or DM me on Twitter! I'll try to give you a hand if you're feeling stuck or overwhelmed. Stay tuned for tomorrow's post where we will cover writing CRUD functions for our new, fancy blog site! If you're feeling squirrely and want to give it a go before then, I encourage you to check out the Firebase documentation.

Back to Top