AppDividend
Latest Code Tutorials

React.js Firebase Tutorial

13,831

Get real time updates directly on you device, subscribe now.

React.js Firebase Tutorial is today’s primary focus. If you do not know, what React.js then go to this tutorial Beginner’s Guide To Setup React Environment on this website and you will know about React.js. It is the popular front end library used by many big companies and created by Facebook. Today we will create a chat application using React.js and Firebase as a backend data service. 

Firebase is the most popular backend data service provider. Firebase is a real-time database service provider. It is API that enables the integration of online chat functionality into their websites. Now, enough talking let us jump into this React.js Firebase Tutorial. You will find more info on their official website https://firebase.google.com/

React.js Firebase Tutorial

Step 1: Create React.js Firebase Tutorial.

Install React Starter Kit project by the following command.

npm install -g create-react-app

Now, create one app using the following command.

create-react-app react-turbo

Your starter kit’s file structure looks like this.

react firebase application

Step 2: Define our application structure.

For this project, we are using a modern CSS framework based on Flexbox called Bulma

So go to the react-turbo  >>  public  >>  index.html and paste the following CDN of Bulma CSS Framework.

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.4.3/css/bulma.css">

We are going to create one simple message app, which is storing the message in the Firebase and will show the message in our application.

If you are working in the React.js application, you need to keep following points in your mind.

  1. You need to identify your components structure then and then you will be able to start the coding. 
  2. We need to give your application proper structure like who will become parent component and who will become child component.
  3. Communication between the components is the significant key point in the React.js. Otherwise, you will end up making a mess of your code, and all your further paths of the code will be blocked, or you will be stuck at some point, and from there you will need to rewrite whole application.

I am going to show you how I have structured my application.

Introduction to Firebase and React

 

In the upper part, our whole component called App.js

It will contain MessageList Component called MessageList.js

MessageList component contains Messages of our application getting from Firebase Database.

MessageBox component is responsible for the add messages form. It will be a textarea through which user can add the new messages.

Go to src  >>  App.js and edit the code.

// App.js

import React, { Component } from 'react';

class App extends Component {
  render() {
    return (
      <div>
        React Firebase Tutorial
      </div>
    );
  }
}

export default App;

Start the development server by typing following command.

npm start

The development server is started, and you can see in the browser by going following  URL. It will automatically open the browser window.

http://localhost:3000/

We can see that in browser “React Firebase Tutorial.

Related Posts
1 of 20

Step 3: Define app.js file.

Now, we need to create two components. So first create one folder inside src folder and name it as “components.

App.js will be by default provided by React Application.

App.js file is included in index.js file.

// index.js

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';

ReactDOM.render(<App />, document.getElementById('root'));
registerServiceWorker();

So, the main component of our app is App.js

The first component would be “MessageList.js.”

The second component would be “Message.js.”

Step 4: Create MessageList component.

Create the first component called MessageList.js

// MessageList.js

import React, {Component} from 'react';

class MessageList extends Component {
  render(){
    return (
      <div>
        MessageList Component
      </div>
    )
  }
}

export default MessageList

This component contains all the messages to display. So first we need to define an array of messages in the constructor.

// MessageList.js

constructor(props){
    super(props);
    this.state  = {
      messages: []
    }
  }

If we are going to use the constructor in our app, then we call the props from the parent component. Otherwise, it will not work.

Here I have to define default state of messages array, and it is empty. But in future, we need to fill this with the messages given by Firebase Application.

Now, include this component into the App.js, our main component.

// MessageList.js

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

class App extends Component {
  render() {
    return (
      <div>
        <MessageList />
      </div>
    );
  }
}

export default App;

You will see in the browser that “MessageList Component” will display.

Step 5: Create header component.

We also create one another component called Header.js

// Header.js

import React, {Component} from 'react';

class Header extends Component {

  render(){
    return (
      <nav className="navbar">
        <div className="navbar-brand">
          <a className="navbar-item" href="http://bulma.io">
            {this.props.title}
          </a>
        </div>
      </nav>
    )
  }
}
export default Header

Here I have provided one property called title, you can see like {this.props.title}

Remember that I have used Bulma as CSS Framework so, the class names are may not be familiar to you.

In React.js class is reserved keyword so instead of using class in CSS property use className

Include this Header in the App.js file.

// App.js

render(){
     return (
      <div className="container">
          <Header title="Simple Firebase App" />
          <MessageList />
      </div>
    );
}

Step 6: Create Message component.

Create one component called Message.js and put the following code in it.

// Message.js

import React, {Component} from 'react';

class Message extends Component {

  render(){
    return (
      <div>
        {this.props.message}
      </div>
    )
  }
}
export default Message

Here we get all the messages one by one as a property of MessageList component.

Step 7: Configure Firebase Database.

Now we need to create and configure Firebase Database

Firebase is a product of Google, so you need to have at least one Google account.

Now, go to this URL: https://firebase.google.com/

If you are signed in to Google, then you will see the following screen.

React and Firebase Application

Now, click the Go To Console button. You will see the following screen.

Firebase Database Service

Now, click the Add Project title. 

Create Firebase Project

Name your project and select your country and click the Create Project button. You will see this screen.

Firebase Authentication

 

Now, here we need to configure our project for the web. So click “Add Firebase to your web app” button.

You will find two scripts file with your project related configurations. You need to copy 2nd script with the config object.

We include Firebase via NPM so, go to the terminal and type following command

npm i firebase --save

Include this package in App.js file.

// App.js

import firebase from 'firebase';

In the App.js file’s constructor, we are going to configure the Firebase. So Copy the following code and put it in your constructor.

// App.js

var config = {
    apiKey: "",
    authDomain: "",
    databaseURL: "",
    projectId: "appdividend-c8a0f",
    storageBucket: "",
    messagingSenderId: ""
  };
  firebase.initializeApp(config);

I have emptied out all the values, but you have those value just copy paste it from the Firebase Console or copy from your console and paste it here. Now, we have successfully connected with our Firebase database service.

Step 8: Include the config object of Firebase.

But we need to use this service in the MessageList component. Remember this component is responsible for the getting all the messages from the database. So we need to pass this Firebase reference to this component via properties.

So our App.js file is looking like this.

// App.js

import React, { Component } from 'react';
import MessageList from './components/MessageList';
import Header from './components/Header';
import firebase from 'firebase';

class App extends Component {

constructor(props){
  super(props);
  var config = {
    apiKey: "",
    authDomain: "",
    databaseURL: "",
    projectId: "",
    storageBucket: "",
    messagingSenderId: ""
  };
  firebase.initializeApp(config);
}

  render() {
    return (
      <div className="container">
            <Header title="Simple Firebase App" />
            <div className="columns">
              <div className="column is-3"></div>
              <div className="column is-6">
                <MessageList db={firebase} />
              </div>
            </div>
        </div>
    );
  }
}

export default App;

Step 9: Create component called MessageBox.js

Create one another component inside components folder called “MessageBox.js.

// MessageBox.js

import React, {Component} from 'react';

class MessageBox extends Component {
  render() {
        return (
          <form>
            <textarea
                className="textarea"
                placeholder="Type a message"
                cols="100">
              </textarea>
          </form>
        )
  }
}

export default MessageBox

Include this file in App.js.  So our file will look like this.

// App.js

import React, { Component } from 'react';
import MessageList from './components/MessageList';
import ChannelList from './components/ChannelList';
import MessageBox from './components/MessageBox';
import Header from './components/Header';
import firebase from 'firebase';

class App extends Component {

  constructor(props){
    super(props);
    firebase.initializeApp({
      apiKey: "",
      authDomain: "",
      databaseURL: "",
      projectId: "",
      storageBucket: "",
      messagingSenderId: ""
    });
  }

  render(){
    return (
      <div className="container">
            <Header title="Simple Firebase App" />
            <div className="columns">
              <div className="column is-3"></div>
              <div className="column is-6">
                <MessageList db={firebase} />
              </div>
            </div>
            <div className="columns">
              <div className="column is-3"></div>
              <div className="column is-6">
                <MessageBox db={firebase} />
              </div>
            </div>
        </div>
    )
  }
}

export default App;

Step 10: Setup database rules.

Now, we need to add the message to our database and make sure that in your firebase app you will have both permissions and read as well as write.

So go to your console and click in the Database section on the left side. Now go to the rules tab. You need to give both permissions to true like the following image.

Firebase Database Permission

 

I am ignoring all the Securities issues right now because It’s a demo app, but in real-time, you need to provide proper authentication for that.

Switch to your editor and open the MessageBox.js component. Put the following code in it. I will explain you this.

// MessageBox.js

import React, {Component} from 'react';
import trim from 'trim';

class MessageBox extends Component {

  constructor(props){
    super(props);
    this.onChange = this.onChange.bind(this);
    this.onKeyup = this.onKeyup.bind(this);
    this.state = {
      message: ''
    };
  }
  onChange(e){
      this.setState({
        message: e.target.value
      });
  }
  onKeyup(e){
    if(e.keyCode === 13 && trim(e.target.value) !== ''){
      e.preventDefault();
      let dbCon = this.props.db.database().ref('/messages');
      dbCon.push({
        message: trim(e.target.value)
      });
      this.setState({
        message: ''
      });
    }
  }
  render() {
    return (
      <form>
        <textarea
            className="textarea"
            placeholder="Type a message"
            cols="100"
            onChange={this.onChange}
            onKeyUp={this.onKeyup}
            value={this.state.message}>
          </textarea>
      </form>
    )
  }
}

export default MessageBox

Here, First of all, I have downloaded one more package called ‘trim‘ via NPM and imported as well.

Now, I have used Two events of any Textbox or Textarea, which is

  1. onChange()
  2. onKeyUp()

onChange() event set the current state of textarea value, and onKeyUp() will fire when someone presses the enter key to send the message. Trim package is used for trailing the whitespace from the typed message.

We are using the Firebase database instance from the properties provided by App.js

Now, pushing(saving) the typed value to the Firebase in onKeyUp() function.

Okay, finally switch the http://localhost:3000 You will see something like this.

React Firebase Chat App

 

Now, fill the new message and press enter.

If the Firebase is configured correctly then, you will be able to see the following screen.

Firebase React Tutorial

 

Firebase will automatically generate the new key for us and save our message into the database.

Step 11: Display the messages in our application.

Now, all we need is to display the message in our application. So put the following code in our MessageList.js file

// MessageList.js

import React, {Component} from 'react';
import Message from './Message';
import _ from 'lodash';

class MessageList extends Component {
  constructor(props){
    super(props);
    this.state = {
      messages: []
    };
    let app = this.props.db.database().ref('messages');
    app.on('value', snapshot => {
      this.getData(snapshot.val());
    });
  }

  getData(values){
    let messagesVal = values;
    let messages = _(messagesVal)
                      .keys()
                      .map(messageKey => {
                          let cloned = _.clone(messagesVal[messageKey]);
                          cloned.key = messageKey;
                          return cloned;
                      })
                      .value();
      this.setState({
        messages: messages
      });
  }

  render() {
    let messageNodes = this.state.messages.map((message) => {
      return (
        <div className="card">
          <div className="card-content">
            <Message message = {message.message} />
          </div>
        </div>
      )
    });
    return (
      <div>
        {messageNodes}
      </div>
    );
  }
}

export default MessageList

I am explaining you, what is happening here.

First, I would like to download a new package from NPM called ‘lodash.’

If you want to program functionally and you need to deal with lots of arrays as well as objects then in javascript you should definitely use this library. It is quite a famous library in Functional JavaScript Programming.

In the constructor, I am using the database reference to call the Firebase server reference to get the messages data. It will return a Promise, and when It resolves, we get our data. Here the URL or Reference for the Firebase is ‘/messages.’ Messages are one of the nodes of firebase, and we are getting all of its children as data. 

The data is returned as an Object, and we are storing this values in an array that is why we are using the lodash module to convert an Object into an Array.

Finally, iterate an array and put the value in Message component as a property and Message component displays the messages.

Now, go to the http://localhost:3000/

You will see one message is displaying and in below message box is also there.

React Firebase Simple Tutorial

Enter a 4-5 messages more, and without refresh, the messages will be displayed.

Simple React Tutorial

 

You can learn more about Firebase like how to update and delete a record. I have not covered in this tutorial but will cover in next React tutorial. For more, refer:  https://firebase.google.com/docs/reference/js/firebase.database

Now, Finally, Our today’s topic React.js Firebase Tutorial is over.

I am putting this code in Github Repo.

Githubhttps://github.com/KrunalLathiya/React-and-Firebase-Tutorial

Steps To Use Github Code:

  1. Clone the repo.
  2. Go to the project and run “npm install”
  3. Go to the https://firebase.google.com/ Firebase console and configure the database.
  4. Open a browser and go to http://localhost:3000

 

Still Doubt? Ask in a comment below. I am happy to help you.

16 Comments
  1. Brad says

    Has anyone done this?
    Have an example of the end result I can play with before trying it?

    Thank you!!

    1. Krunal says

      You can download the repository and check it. It’s the matter of at max 10 mins.

  2. Furasesa says

    Thank you very much. It much easier and worked. thanks again 🙂

  3. Elliot says

    Just curious, what theme are you using in atom for the file tree icons? Great tutorial though, thanks!

  4. Carmen says

    Muchas gracias 🙂 Excelente y sencillo

  5. Yash Gupta says

    Hello @Krunal Can you give an idea about how to make a private chat

  6. Piotr says

    Thank You! Nice tutorial.

  7. akbar zubairi says

    don’t really need lodash and all those codes to convert to Array, not that anything wrong with it or going against your long codes but you simply push value to an array and set that to state..let me show you..

    let app = this.props.db.database().ref(“messages”);
    app.on(“value”, snapshot => {
    var items = [];
    snapshot.forEach(item => {
    items.push(item.val());
    });

    this.setState({
    messages: items
    });
    });

    that is it no need getData function

    1. AJIT GOEL says

      strongly agree.

  8. Deekshit says

    Awesome, thank you.

  9. AMAN SETH says

    WHEN I PRESS ENTER THE MESSAGE IS NOT SENT IT MAKES THE CURSOR MOVE TO NEXT LINE.

    1. Robert Wafle says

      Hi Aman, did you figure it out?

  10. shanti gola says

    thank you so much for posting such a nice article for the newbies …it really help a lot !!

  11. Robert Wafle says

    Hi. In Step 4 after “Now, include this component into the App.js, our main component.”

    The comment at the top of the file that is supposed to be App.js reads MessageList.js

  12. adnan says

    Hi, thanks for this tuto
    who tels MessageList to update himself each time a message is entered ? is it the promise or a behaviour of react ?

  13. Mako says

    Where did ChannelList appear all of a sudden?

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.