Building an App with firebase and react hooks in simple way

This article is going to be a complete tutorial about Building a Note application with firebase and react hooks.

Recent Articles,

Building Bookmark Manager using nodejs and mysql

Building a Piano with React Hooks

Table of Content

If you are completely new to react development, checkout this course from wesbos.

Well. It's Demo time..

Let's how to build one something like this using firebase with react hooks.

Firebase Setup

Firstly, we will setup firebase and get the credentials for our application.

goto Firebase and create a project

firebase setup 1

Click on Web to get the credentials for the project

Screenshot 2020 02 20 at 1 02 07 AM

firebase setup 2

Integrating firebase and react hooks

create a react project using create-react-app command,

1npx create-react-app note-firebase
2npm i firebase styled-components

After that, create a file firebase.js and add the firebase credentials

1import firebase from "firebase/app"
2
3import "firebase/firestore"
4
5const firebaseConfig = {
6 apiKey: `${process.env.APIKEY}`,
7 authDomain: `${process.env.AUTH_DOMAIN}`,
8 databaseURL: `${process.env.DATABASE_URL}`,
9 projectId: `${process.env.PROJECTID}`,
10 storageBucket: `${process.env.STORAGE_BUCKET}`,
11 messagingSenderId: `${process.env.MESSAGE_SENDER_ID}`,
12 appId: `${process.env.APP_ID}`,
13 measurementId: `${process.env.MEASUREMENT_ID}`,
14}
15// Initialize Firebase
16firebase.initializeApp(firebaseConfig)
17// firebase.analytics();
18
19export default firebase

you might be wondering where do we set the environment variable, let's do that process,

1npm install env-cmd

env-cmd is used to set the environment variable in react applications. Then, add that in react scripts.

1"start": "env-cmd -f .env.development react-scripts start",

Note: Don't forget to create .env.development file and add the credentials.

Developing Note Application with Firebase and Reack Hooks

We will be using styled component for React Components. If you are new to the concept of styled component, checkout this article

Firstly, to check firebase is working correctly with react. let's connect it in the App.js to use firebase with react hooks.

1import React from "react"
2import "./App.css"
3
4import firebase from "./firebase"
5
6function App() {
7 firebase
8 .firestore()
9 .collection("notes")
10 .add({
11 title: "Working",
12 body: "This is to check the Integration is working",
13 })
14 return (
15 <div className="App">
16 <h2>Note Taking App</h2>
17 <p>using React Hooks and Firebase</p>
18 <h3>Notes : </h3>
19 </div>
20 )
21}
22
23export default App

it will insert the data into the notes collection. let's check whether it's working properly by running the command,

1npm run start

Screenshot 2020 02 20 at 11 47 44 PM

Woohoo..it's working. Let's see how to implement it in our components.

create two files AddNote.js and NoteLists.js where AddNote is to Handle the logics for adding a note.

Whereas, NoteLists handles all the list items of notes.

AddNote.js

add the following code in AddNote.js

1import React, { useState } from "react"
2import styled from "styled-components"
3import firebase from "./firebase"
4const AddNoteDiv = styled.div`
5 display: flex;
6 width: 40%;
7 flex-direction: column;
8 margin: 30px auto;
9 padding: 5px;
10`
11
12const InputTitle = styled.input`
13 padding: 0.5em;
14 border: none;
15 background: #f4f4;
16 margin-bottom: 10px;
17 border-radius: 3px;
18`
19
20const BodyTextArea = styled.textarea`
21 padding: 0.5em;
22 border: none;
23 height: 80px;
24 background: #f4f4;
25 margin-bottom: 10px;
26 border-radius: 3px;
27`
28
29const Button = styled.div`
30 background: blue;
31 color: white;
32 font-size: 1em;
33 padding: 10px;
34 cursor: pointer;
35 border-radius: 3px;
36`
37
38const AddNote = () => {
39 const [title, setTitle] = useState("")
40 const [body, setBody] = useState("")
41
42 const addNote = () => {
43 firebase
44 .firestore()
45 .collection("notes")
46 .add({
47 title,
48 body,
49 })
50
51 setTitle("")
52 setBody("")
53 }
54
55 return (
56 <AddNoteDiv>
57 <InputTitle value={title} onChange={e => setTitle(e.target.value)} />
58 <BodyTextArea value={body} onChange={e => setBody(e.target.value)} />
59 <Button onClick={addNote}>Add Note</Button>
60 </AddNoteDiv>
61 )
62}
63
64export default AddNote

Here, we create text area and text input and store those values in react state using useState Hooks.

Once the user Clicks the Add Note button, we send those state values to firebase.

NoteLists.js

1import React, { useState, useEffect } from "react"
2import styled from "styled-components"
3import firebase from "./firebase"
4
5const ListsDiv = styled.div`
6 width: 40%;
7 height: 100%;
8 background: #dedede;
9 margin: 30px auto;
10 padding: 20px;
11`
12
13const ListItemDiv = styled.div`
14 background: #b2c4db;
15 border-radius: 5px;
16 position: relative;
17`
18
19const ListTitleDiv = styled.div`
20 font-size: 24px;
21 color: black;
22 font-weight: bold;
23 margin: 3px;
24`
25
26const ListItemDetailDiv = styled.p`
27 font-size: 18px;
28 color: black;
29 margin: 3px;
30 max-height: 80px;
31 overflow: auto;
32`
33
34const ListItemDeleteButton = styled.button`
35 border-radius: 5px;
36 background: #c26c61;
37 color: white;
38 position: absolute;
39 width: 15px;
40 height: 15px;
41 top: 5px;
42 right: 10px;
43 outline: none;
44`
45
46function useLists() {
47 const [lists, setLists] = useState([])
48
49 useEffect(() => {
50 firebase
51 .firestore()
52 .collection("notes")
53 .onSnapshot(snapshot => {
54 const lists = snapshot.docs.map(doc => ({
55 id: doc.id,
56 ...doc.data(),
57 }))
58
59 setLists(lists)
60 })
61 }, [])
62
63 return lists
64}
65
66const NoteLists = () => {
67 const lists = useLists()
68
69 const handleOnDelete = id => {
70 firebase
71 .firestore()
72 .collection("notes")
73 .doc(id)
74 .delete()
75 }
76
77 return (
78 <ListsDiv>
79 {lists.map(list => {
80 return (
81 <ListItemDiv>
82 <ListTitleDiv>{list.title}</ListTitleDiv>
83 <ListItemDetailDiv>{list.body}</ListItemDetailDiv>
84 <ListItemDeleteButton onClick={() => handleOnDelete(list.id)} />
85 </ListItemDiv>
86 )
87 })}
88 </ListsDiv>
89 )
90}
91
92export default NoteLists

Here, you might be wondering what is a useLists. you might have not seen something like this in React Hooks. well, it is a custom hook.

Why we need a Custom Hook?. That's a good question to ask. Before Hooks, if we want to share the stateful function or logic. we either use Render Props or Higher Order Components.

After Hooks, we tend to use it for all our component development. How can share a stateful function which uses Hooks. There comes the concept of Custom Hooks.

Custom Hooks is a function whose name starts with use keyWord and it may call other Hooks

Note : use KeyWord is for understanding purpose.

Like we said, Here useLists is a custom hook which calls the useState and useEffect.

Everytime data is added in the firebase, useLists hooks will be called to update the list state.

App.js will be like

1import React from "react"
2import AddNote from "./AddNote"
3import NoteLists from "./NoteLists"
4import "./App.css"
5
6function App() {
7 return (
8 <div className="App">
9 <h2>Note Taking App</h2>
10 <p>using React Hooks and Firebase</p>
11 <AddNote />
12 <h3>Notes : </h3>
13 <NoteLists />
14 </div>
15 )
16}
17
18export default App

Complete Source code can be found here

Summary

This article explains how to get started with firebase and react hooks. We will come up with some advanced Concepts in Firebase and React Hooks using a real time example in upcoming articles.

Until then, Happy Coding :-)

To Read More

Kubernetes for Nodejs developers

Do you keep hearing the word kubernetes in the tech community and you couldn't u...

TypeScript Interfaces vs Types

In this article, we will see what are interfaces and types and the difference be...

How to find project ideas to practi...

Ever wondered what how to get a real world experience on web development while w...

Building a Production-grade Nodejs,...

This article is the first part of building a production grade nodejs,graphql and...

Modern React Redux Tutorials with R...

This tutorial explain how you can build an application using modern react redux ...

Building a Piano with React Hooks

In this article, we will see how to build a piano with react hooks. Building a P...

TypeScript Basics - The Definitive ...

In this article, we will learn some basics of typescript which helps you to deve...

Here's why podman is more secured t...

In this article we will see about podman and why it is more secured way to run c...

What is gRPC ? How to implement gRP...

Everyone talks about gRPC. Have you ever wonder how it works or how to implement...