This article is going to be a complete tutorial about Building a Note application with firebase and react hooks.
Building Bookmark Manager using nodejs and mysql
Building a Piano with React Hooks
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.
Firstly, we will setup firebase and get the credentials for our application.
goto Firebase and create a project
Click on Web to get the credentials for the project
create a react project using create-react-app command,
1npx create-react-app note-firebase2npm i firebase styled-components
After that, create a file firebase.js and add the firebase credentials
1import firebase from "firebase/app"23import "firebase/firestore"45const 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 Firebase16firebase.initializeApp(firebaseConfig)17// firebase.analytics();1819export 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.
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"34import firebase from "./firebase"56function App() {7 firebase8 .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}2223export 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
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.
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`5678910`1112const InputTitle = styled.input`131415161718`1920const BodyTextArea = styled.textarea`21222324252627`2829const Button = styled.div`30313233343536`3738const AddNote = () => {39 const [title, setTitle] = useState("")40 const [body, setBody] = useState("")4142 const addNote = () => {43 firebase44 .firestore()45 .collection("notes")46 .add({47 title,48 body,49 })5051 setTitle("")52 setBody("")53 }5455 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}6364export 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.
1import React, { useState, useEffect } from "react"2import styled from "styled-components"3import firebase from "./firebase"45const ListsDiv = styled.div`67891011`1213const ListItemDiv = styled.div`14151617`1819const ListTitleDiv = styled.div`2021222324`2526const ListItemDetailDiv = styled.p`272829303132`3334const ListItemDeleteButton = styled.button`35363738394041424344`4546function useLists() {47 const [lists, setLists] = useState([])4849 useEffect(() => {50 firebase51 .firestore()52 .collection("notes")53 .onSnapshot(snapshot => {54 const lists = snapshot.docs.map(doc => ({55 id: doc.id,56 ...doc.data(),57 }))5859 setLists(lists)60 })61 }, [])6263 return lists64}6566const NoteLists = () => {67 const lists = useLists()6869 const handleOnDelete = id => {70 firebase71 .firestore()72 .collection("notes")73 .doc(id)74 .delete()75 }7677 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}9192export 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"56function 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}1718export default App
Complete Source code can be found here
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 :-)
No spam, ever. Unsubscribe anytime.