{"id":255231,"date":"2017-06-02T06:16:46","date_gmt":"2017-06-02T13:16:46","guid":{"rendered":"http:\/\/css-tricks.com\/?p=255231"},"modified":"2017-09-06T07:31:19","modified_gmt":"2017-09-06T14:31:19","slug":"intro-firebase-react","status":"publish","type":"post","link":"https:\/\/css-tricks.com\/intro-firebase-react\/","title":{"rendered":"Intro to Firebase and React"},"content":{"rendered":"

Let’s take a look at building something using Firebase and React. We’ll be building something called Fun Food Friends<\/strong>, a web application for planning your next potluck, which hopefully feels like something rather “real world”, in that you can imagine using these technologies in your own production projects. The big idea in this app is that you and your friends will be able to log in and be able to see and post information about what you’re planning to bring to the potlock. <\/p>\n

<\/p>\n

\n

Article Series:<\/h4>\n
    \n
  1. Intro to Firebase and React (You are here!)<\/li>\n
  2. User Authentication<\/a><\/li>\n<\/ol>\n<\/div>\n

    When we’re finished, it will look like this:<\/p>\n

    \"\"
    Our example app: Fun Food Friends<\/figcaption><\/figure>\n

    This article assumes you already have some basic knowledge of how React works and maybe built a few small apps with React. If you haven’t, I would recommend checking out a series like Wes Bos’ React for Beginners<\/a> first before continuing on.<\/p>\n

    What is Firebase?<\/h3>\n

    Google’s Firebase<\/a> is a cloud-based database hosting service that will set up a database for you and host it, as well as offer you the tools to interact with it. You can use it to store and retrieve data in real time. That’s not all Firebase does, it can do more things like handle user authentication and store files, but we’ll be mainly focusing on data storage.<\/p>\n

    The data storage ability of Firebase make it a perfect fit for React. A persistent, real-time backend for your application to plug in to!<\/p>\n

    How does Firebase store data?<\/h3>\n

    Firebase stores data as a giant object with key-value pairs. Unlike JSON or JavaScript objects, there are no arrays in Firebase.<\/p>\n

    A Firebase database might look something like this:<\/p>\n

    {\r\n      \"groceries\": {\r\n        \"-KjQTqG3R2dPT8s2jylW\": \"tomato\",\r\n        \"-KjQTrds1feHT3GH_29o\": \"pasta\",\r\n        \"-KjQTsmfBR8zN1SwPPT8\": \"milk\",\r\n        \"-KjQTtnzt_jJZPoCHWUM\": \"sugar\"\r\n      },\r\n      \"users\": {\r\n        \"name\": {\r\n          \"-KjQTyIfKFEVMYJRZ09X\": \"simon\",\r\n          \"-KjQU-Xuy5s7I-On9rYP\": \"ryan\",\r\n          \"-KjQU0MYVeKRsLuIQCYX\": \"sylvia\"\r\n        }\r\n      }\r\n}<\/code><\/pre>\n

    For more information on the nuances of structuring data in Firebase, you can read the amazing Firebase documentation<\/a>.<\/p>\n

    Ready to start? Let’s dig in!<\/p>\n

    Getting Started: Setting up Our App<\/h3>\n

    We’ll start by using the incredibly handy `create-react-app` package in order to quickly set up a new React project without having to worry about any build configuration. Open up your command line, and type the following:<\/p>\n

    npm install -g create-react-app\r\n    \r\ncreate-react-app fun-food-friends\r\ncd fun-food-friends\r\nyarn add firebase --dev\r\nyarn start<\/code><\/pre>\n

    This will boot up your app in the browser, and start a watch task in your terminal so that we can begin hacking away at the project. We’re also installing the `firebase` package here as we’ll need it for the next step.<\/p>\n

    Creating our Firebase Database<\/h3>\n

    Now that our app is set up, we’ll need to create an account and database on Firebase so that we can link up our application to it.<\/p>\n

    Head on over to Firebase’s website<\/a>, and click Get Started.<\/b><\/p>\n

    \"\"<\/figure>\n

    This will take you to a page where you\u2019ll be asked to authenticate with your Google account. Select the account that you\u2019d like this project to be affiliated with, and press OK<\/b>.<\/p>\n

    This should take you to the Firebase console, which looks something like this:<\/p>\n

    \"\"<\/figure>\n

    Now let’s create our project’s database. Click Add Project<\/b>. Let’s call it “fun-food-friends” and press OK<\/b>. <\/p>\n

    This will take you to your app’s dashboard, which looks like this:<\/p>\n

    \"\"<\/figure>\n

    Since we’ll be building a web app, select Add Firebase to your web app<\/b>. This will trigger a popup with some code that looks like this:<\/p>\n

    <script src=\"https:\/\/www.gstatic.com\/firebasejs\/3.9.0\/firebase.js\"><\/script>\r\n<script>\r\n  \/\/ Initialize Firebase\r\n  var config = {\r\n     apiKey: \"AIzaSyDblTESEB1SbAVkpy2q39DI2OHphL2-Jxw\",\r\n    authDomain: \"fun-food-friends-eeec7.firebaseapp.com\",\r\n    databaseURL: \"https:\/\/fun-food-friends-eeec7.firebaseio.com\",\r\n    projectId: \"fun-food-friends-eeec7\",\r\n    storageBucket: \"fun-food-friends-eeec7.appspot.com\",\r\n    messagingSenderId: \"144750278413\"\r\n  };\r\n  firebase.initializeApp(config);\r\n<\/script><\/code><\/pre>\n

    Since we’ll be importing Firebase into our project using ES6 modules, we won’t need those script tags. That config<\/code> object is important though: it’s how we authenticate our React application with our Firebase database. <\/p>\n

    Hooking up our App to Firebase<\/h3>\n

    Copy that whole config object, and head back over to your React project. Find your `src` folder, and create a file called `firebase.js`. Inside of it, let’s import firebase, our config, and initialize our app:<\/p>\n

    \/\/ src\/firebase.js\r\nimport firebase from 'firebase'\r\nconst config = {\r\n    apiKey: \"AIzaSyDblTESEB1SbAVkpy2q39DI2OHphL2-Jxw\",\r\n    authDomain: \"fun-food-friends-eeec7.firebaseapp.com\",\r\n    databaseURL: \"https:\/\/fun-food-friends-eeec7.firebaseio.com\",\r\n    projectId: \"fun-food-friends-eeec7\",\r\n    storageBucket: \"fun-food-friends-eeec7.appspot.com\",\r\n    messagingSenderId: \"144750278413\"\r\n};\r\nfirebase.initializeApp(config);\r\nexport default firebase;<\/code><\/pre>\n

    One last thing we’ll need to do before we can dive into roughing out our App. We need to temporarily disable authentication requirements on our app so that we can add and remove items without needing to have any kind of user authentication flow. <\/p>\n

    From the Firebase Dashboard, on the left-hand side of the screen, you’ll notice that there is a Database tab. Click on it. Then, on the right-hand side, under the subheading Realtime Database<\/b>, you’ll see a Rules<\/b> tab. This will cause an object to appear that looks something like this:<\/p>\n

    {\r\n    \"rules\": {\r\n      \".read\": \"auth != null\",\r\n      \".write\": \"auth != null\"\r\n    }\r\n}<\/code><\/pre>\n

    We need to set .read<\/code> and .write<\/code> to both be equal to true<\/code>, otherwise later, when we try to add data to our database from our application, Firebase won’t let us. When you’re finished, it should look something like this:<\/p>\n

    \"\"<\/figure>\n

    Make sure to click the Publish<\/b> button.<\/p>\n

    And that’s all there is to hooking up our database! Anytime we need a component of our application to connect with our Firebase database, we simply need to import our firebase module and we’ll have direct reference to it.<\/p>\n

    Building out our App’s Rough Skeleton<\/h3>\n

    Let’s build out a rough HTML skeleton for our application. We’ll build a simple form with two inputs:<\/p>\n

      \n
    1. A field where the user can submit their name<\/li>\n
    2. A field where the user can enter what food they’re bringing to the potluck.<\/li>\n<\/ol>\n

      Since our app is quite simple, we’ll keep everything inside of one main component, `App.js`. Open up `src\/App.js`, and remove the `App` component, replacing it with this basic skeleton:<\/p>\n

      import React, { Component } from 'react';\r\nimport logo from '.\/logo.svg';\r\nimport '.\/App.css';\r\n\r\nclass App extends Component {\r\n  render() {\r\n    return (\r\n      <div className='app'>\r\n        <header>\r\n            <div className='wrapper'>\r\n              <h1>Fun Food Friends<\/h1>\r\n