Codementor Events

All you need is React & Firebase

Published Feb 13, 2017Last updated Aug 22, 2017
All you need is React & Firebase

A lot of modern-day fatigue from developing web applications results from the number of technologies and services we have to use simultaneously.

The question is: how can we maximize our effectivity with minimum technologies. Ideally the technologies we choose would be established and have great community support.

In this article we'll look at two technologies — established and strong community support — that enable us to create live web apps.

Prerequisites:

  • You know some React, at least the basics
  • You have Node.js and NPM installed
  • You know how to use command line, at least the basics

So here's what we are going to do today:

  • Log into Firebase Console and create a new project
  • Create a simple React application with create-react-app
  • Deploy it to Firebase Hosting with one simple command
  • Wire data in your app to Firebase Database

Here are some topics that will not be covered in this tutorial:

  • Secure your data with Firebase Database Rules and Firebase Auth
  • Store your images and other files on Firebase Storage
  • Make your apps look like normal websites with react-route
  • Create and admin section, or conditionally display editing tools
  • Use your own domain

With a little more information and experience, you should be able to perform these tasks with no problem!

Log into Firebase Console and Create a New Project

Open your browser at firebase.google.com, sign in with your Google account, create new project, and choose a name for your new web application. Firebase will generate a unique address for your web app, and will be ready to host it on it's servers.

Google is generous enough to give 1 GB of storage for free, so you shouldn't be running out of space anytime soon. Check out the Firebase pricing table as well.

Create a Simple React Application with create-react-app

If you don't have create-react-app installed yet, just install it with npm i -g create-react-app.

Now, open your command line and cd into a folder where you'd like your project to be located locally. Go ahead and run create-react-app firebase-and-react, where "firebase-and-react" is the name of your new project — feel free to replace it with your own.

After create-react-app does it's magic installing all react dependencies, cd into your project folder and run npm start. That will open your browser to http://localhost:3000 with a demo react application.

Deploy the App to Firebase Hosting

We are now going to deploy our app to Firebase Hosting.

To do that, we'll need to create a production build with npm run build, which will be located in the build subfolder.

To be able to deploy our app to Firebase Hosting, we'll need to have Firebase command-line interface installed. It can be installed with npm install -g firebase-tools command.

After firebase-tools has been installed, make sure you're in your project folder — go ahead and run firebase init. Firebase command-line interface will guide you through connecting your local project to your Firebase project.

Step 1: Select the Firebase features you want to use. Database and Hosting are selected by default — all you need to do is press enter to go to the next step.

Step 2: Firebase command-line interface will pull up your list of Firebase projects, where you can then choose the corresponding project using the up and down keys.

Step 3: Keep the default for the Database Rules file name and just press enter.

Step 4: Pay attention to the question about public directory, which is the directory that will be deployed and served by Firebase. In our case it is "build", which is the folder where our production build is located. Type "build" and proceed.

Step 5: Firebase will ask you if you want the app to be configured as a single-page app. By default it is "no" — in our case, we could really benefit from the configuration, so we'll type "y" and press enter. Later on you'll be able to use react-router and the URLs will just work.

Step 6: Firebase will warn us that we already have "build/index.html," which we don't want to be overwritten. Type "n" and press enter to keep our own "index.html," generated by our build process earlier.

We are now ready to deploy the app! We'll do that by running firebase deploy. After a few seconds you'll see the URL — where your app is hosted — of your app. It should look something like "https://react-and-firebase-26bee.firebaseapp.com". You should be able to open the URL to view your app.

Rinse & Repeat

Isn't that exciting? We can go back to our app now, make a change, build it with npm run build, and upload a new version with firebase deploy anytime. There's no need to deploy during development though, Firebase Database works well with localhost.

Though we did not discuss the following step, it is a good practice to run common tasks as npm run TASKNAME. It is generally easier to remember to run npm run deploy because you'll have other projects that don't use Firebase for deployment.

To enable the npm run deploy command, open package.json and add "deploy": "firebase deploy" to the scripts object. We'll use this command from now on.

Wire Data in Your App to Firebase Database

To use Firebase Database in our React app, we'll need to import the firebase javascript library and configure it with our Firebase application keys, which can be found in the Firebase Console. Open your project in the Overview section, click on the red button that says "Add Firebase to your web app" and you'll see the keys that we'll need to use.

Make sure you don't rush to copy all of the provided code, we'll do it slightly different — we'll include the firebase package in our react application.

Open the command-line in your project dir and install firebase package into the project by running npm install -S firebase. Don't confuse this with what we did earlier. We simply set up our project to be deployed to Firebase Hosting — we didn't necessarily have to use firebase in our front-end application.

Now we'll use it by creating a file — I will call it fire.js in our src folder.

import firebase from 'firebase'
var config = { /* COPY THE ACTUAL CONFIG FROM FIREBASE CONSOLE */
  apiKey: "unreadablestuff",
  authDomain: "your-domain-name.firebaseapp.com",
  databaseURL: "https://your-domain-name.firebaseio.com",
  storageBucket: "your-domain-name.appspot.com",
  messagingSenderId: "123123123123"
};
var fire = firebase.initializeApp(config);
export default fire;

We are now ready to use Firebase Database, Auth, and Storage in our front-end app!

Before We Can Actually Use Firebase Database

We'll have to be aware that Firebase protects our data with Rules and it's our responsibility to define them so that we can access the data in our app and protect them from those who are not supposed to have access.

If this is your first introduction to Firebase Rules, I suggest you to start by defining completely irresponsible rules that allow everyone to read and write. You'll learn to understand Auth and Rules later: firebase.google.com/docs/database/security/

But for now, open the database.rules.json file in any editor and replace "auth != null" with just true:

{
  "rules": {
    ".read": true,
    ".write": true
  }
}

Run npm run deploy to apply the new database rules.

This will disable any protection of your database data, which will help you get used to how Firebase works.

Some React and Firebase Database

Now it's time to do some read and write in our React app, so let's head to our App.js, import our fire, and do some magic.

For the most basic example, we'll have an input box that will save a message in Firebase Database and the list of entered messages. We'll have to stop there because writing a complete React application is beyond the scope of this article. You'll be free to unleash your creativity with the new knowledge at hand!

Here's what I came up with:

import React, { Component } from 'react';
import fire from './fire';

class App extends Component {
  constructor(props) {
    super(props);
    this.state = { messages: [] }; // <- set up react state
  }
  componentWillMount(){
    /* Create reference to messages in Firebase Database */
    let messagesRef = fire.database().ref('messages').orderByKey().limitToLast(100);
    messagesRef.on('child_added', snapshot => {
      /* Update React state when message is added at Firebase Database */
      let message = { text: snapshot.val(), id: snapshot.key };
      this.setState({ messages: [message].concat(this.state.messages) });
    })
  }
  addMessage(e){
    e.preventDefault(); // <- prevent form submit from reloading the page
    /* Send the message to Firebase */
    fire.database().ref('messages').push( this.inputEl.value );
    this.inputEl.value = ''; // <- clear the input
  }
  render() {
    return (
      <form onSubmit={this.addMessage.bind(this)}>
        <input type="text" ref={ el => this.inputEl = el }/>
        <input type="submit"/>
        <ul>
          { /* Render the list of messages */
            this.state.messages.map( message => <li key={message.id}>{message.text}</li> )
          }
        </ul>
      </form>
    );
  }
}

export default App;

Just replace App.js with the code above and our basic guest book should work. Thanks to the fact that we stored the data at Firebase, and thanks to Firebase Database real-time capabilities, the app can be opened in multiple windows and will be perfectly syncronized.

You can deploy it to your online URL with npm run build && npm run deploy, and it should work there as well.

If you'd like to discuss any of the above, need help, or would like to know where to go from that, let me know in the Codementor chat!

Discover and read more posts from Yuriy Linnyk
get started
post comments50Replies
Solar
10 months ago

The use of visual aids and graphics in this article made it even more engaging and easy to comprehend. benergyperform.com

Daniel Stokholm Thomsen
3 years ago

Failed to compile.

.\src\fire.js
Cannot find module: ‘firebase’. Make sure this package is installed.

What to do?

adrien shen
5 years ago

Sweet thanks! Firebase and React is the fastest way to get a MVP up and running.

Show more replies