How To Implement React CRUD Using Firebase

Introduction

 
In this article, we are going to learn how to do CRUD operations in React applications with Firebase. Previously, we saw an article on Angular CRUD using  Firestore Database and a real time database:  Angular CRUD using Firebase
 
What is ReactJs ?
 
React is an open-source JavaScript library for building user interfaces or UI components. It is maintained by Facebook and a community of individual developers and companies. React can be used as a base in the development of single-page or mobile applications.
 
What is Firebase ?
 
Firebase is a technology that allows us to create web applications without server-side-programming, making development faster and easier. It can control data without thinking about how data is stored and synchronized across different instances of the application in real-time.
 
It is a mobile platform from Google offering a number of different features.These features allow users to save and retrieve data to be accessed from any device or browser.
 
Prerequisites
  • Basic knowledge of React
  • Visual Studio Code must be installed
  • Node JS must be installed
  • Basic Knowledge of Firebase

Create ReactJS project

 
Step 1
 
The very first step is to create a new React.js project by using the following command.
  1. npx create-react-app reactcrud_firebase   
 How To Implement React CRUD Using Firebase
 How To Implement React CRUD Using Firebase
 
Step 2
 
Open the newly created project in Visual Studio code and install React bootstrap in this project by using the following command.
  1. npm install bootstrap
Step 3
 
Now, open the index.js file and import Bootstrap.
  1. import 'bootstrap/dist/css/bootstrap.min.css';
Step 4
 
To integrate our application with Firebase just visit my article, Introduction to Firebase. There I explained in detail how to create an account in Firebase and how to setup the project .
Open your browser then go to Google Firebase Console and log in using your Google account.
 
How To Implement React CRUD Using Firebase
 
Click the Add Project button, name it and click on Continue button.
 
How To Implement React CRUD Using Firebase
 
How To Implement React CRUD Using Firebase
 
Click on Create Project button then wait a few seconds and click on Continue button. You will be redirected to this page.
 
How To Implement React CRUD Using Firebase
 
After then click on </> the icon and you need to add firebase to our app and generate the configuration file. Give the app a name and click on register app.
 
How To Implement React CRUD Using Firebase
 
Next you can see the firebase SDK .
 
How To Implement React CRUD Using Firebase
 
You only need to copy the config object from this page.
 
Step 5
 
We use Firebase module to access the Firebase Firestore Database. Type the below command to install the module.
  1. npm install --save firebase   
Step 6
 
Now create a new file firebase.js and add our configuration code of our firebase. 
  1. import * as firebase from "firebase";  
  2.   
  3. var firebaseConfig = {  
  4.     /* 
  5.     replace this object with yours 
  6.     */  
  7.    apiKey: "AIzaSyCm54M-FmiVcYqeAofITgVdboAzhIpc0tU",  
  8.    authDomain: "reactcrud-d6fad.firebaseapp.com",  
  9.    databaseURL: "https://reactcrud-d6fad.firebaseio.com",  
  10.    projectId: "reactcrud-d6fad",  
  11.    storageBucket: "reactcrud-d6fad.appspot.com",  
  12.    messagingSenderId: "666106395244",  
  13.    appId: "1:666106395244:web:4eb7684e35149228c23649"  
  14. };  
  15.   
  16. // Initialize Firebase  
  17. var fireDb = firebase.initializeApp(firebaseConfig);  
  18.   
  19. export default fireDb.database().ref();  
Step 7
 
Next, open app.js then replace all codes with the following.
  1. import React from 'react'  
  2. import './App.css';  
  3. import StudentInfo from './components/studentInfo ';  

  4. function App() {  
  5.   return (  
  6.     <div className="row">  
  7.       <div className="col-md-8 offset-md-2">  
  8.         <StudentInfo />  
  9.       </div>  
  10.     </div>  
  11.   )  
  12. }  
  13.   
  14. export default App;  
Step 8
 
Now create a component folder and inside it create a file name studentInfo.js to store student information.
  1. import React, { useState, useEffect } from 'react';  
  2. import firebaseDb from "../firebase";  
  3. import AddOrEditStudent from './addOrEditStudent';  
  4.   
  5. const StudentInfo= () => {  
  6.   
  7.     var [currentId, setCurrentId] = useState('');  
  8.     var [studentObjects, setStudentObjects] = useState({})  

  9.     useEffect(() => {  
  10.         firebaseDb.child('Student').on('value', snapshot => {  
  11.             if (snapshot.val() != null) {  
  12.                 setStudentObjects({  
  13.                     ...snapshot.val()  
  14.                 });  
  15.             }  else{
  16.                setStudentObjects({});
  17.             }
  18.         })  
  19.     }, [])  
  20.   
  21.   
  22.     const addOrEdit = (obj) => {  
  23.         if (currentId === '')  
  24.             firebaseDb.child('Student').push(  
  25.                 obj,  
  26.                 err => {  
  27.                     if (err)  
  28.                         console.log(err)  
  29.                     else  
  30.                         setCurrentId('')  
  31.                 })  
  32.         else  
  33.             firebaseDb.child(`Student/${currentId}`).set(  
  34.                 obj,  
  35.                 err => {  
  36.                     if (err)  
  37.                         console.log(err)  
  38.                     else  
  39.                         setCurrentId('')  
  40.                 })  
  41.     }  
  42.   
  43.     const onDelete = id => {  
  44.         if (window.confirm('Are you sure to delete this record?')) {  
  45.             firebaseDb.child(`Student/${id}`).remove(  
  46.                 err => {  
  47.                     if (err)  
  48.                         console.log(err)  
  49.                     else  
  50.                         setCurrentId('')  
  51.                 })  
  52.         }  
  53.     }  
  54.   
  55.     return (  
  56.         <div className="card">  
  57.             <div className="card-body pb-0">  
  58.                 <div className="card">  
  59.                     <div className="card-header main-search dash-search">  
  60.                         <h3>  
  61.                             Student Information Details  
  62.                     </h3>  
  63.                     </div>  
  64.                 </div>  
  65.                 <div className="row">  
  66.                     <AddOrEditStudent {...({ currentId, studentObjects, addOrEdit })}></AddOrEditStudent>
  67.                     <div className="col-12 col-md-12">  
  68.                         <div className="card">  
  69.                             <div className="card-header">Student Management</div>  
  70.                             <div className="card-body position-relative">  
  71.                                 <div className="table-responsive cnstr-record product-tbl">  
  72.                                     <table className="table table-bordered heading-hvr">  
  73.                                         <thead>  
  74.                                             <tr>  
  75.                                                 <th className="active">Full Name</th>  
  76.                                                 <th>Roll No</th>  
  77.                                                 <th>Subject</th>  
  78.                                                 <th>Class</th>  
  79.                                                 <th width="60"> </th>  
  80.                                                 <th width="60"> </th>  
  81.                                             </tr>  
  82.                                         </thead>  
  83.                                         <tbody>  
  84.                                             {  
  85.                                                 Object.keys(studentObjects).map((key) => (  
  86.                                                     <tr key={key}>  
  87.                                                         <td>{studentObjects[key].FullName}</td>  
  88.                                                         <td>{studentObjects[key].RollNo}</td>  
  89.                                                         <td>{studentObjects[key].Subject}</td>  
  90.                                                         <td>{studentObjects[key].Class}</td>  
  91.   
  92.                                                         <td className="case-record">  
  93.                                                             <button type="button" className="btn btn-info"  
  94.                                                                 onClick={() => { setCurrentId(key) }}>Edit</button>  
  95.   
  96.                                                         </td>  
  97.                                                         <td> <button type="button" className="btn btn-danger"  
  98.                                                             onClick={() => { onDelete(key) }}>Delete</button></td>  
  99.                                                     </tr>  
  100.                                                 ))  
  101.                                             }  
  102.                                         </tbody>  
  103.                                     </table>  
  104.                                 </div>  
  105.                             </div>  
  106.                         </div>  
  107.                     </div>  
  108.                 </div>  
  109.             </div>  
  110.         </div>  
  111.     );  
  112. }  
  113.   
  114. export default StudentInfo;  
For Add and Edit we are getting data from its child component which is addEditStudent and pushing the data in. The object for adding current id will be blank.
 
How To Implement React CRUD Using Firebase
 
Follow the below code for fetching the created data from the firestore database.
 
How To Implement React CRUD Using Firebase
 
Follow the below code for delete operation. It will remove the records from firebase using .remove() method. 
 
How To Implement React CRUD Using Firebase
 
Follow the below code for binding the fetched records in react jsx. 
 
How To Implement React CRUD Using Firebase
 
Step 9
 
To seperate it out we are creating one more component, addEditStudent.js, inside component folder which is a child component of studentInfo.js file .
  1. import React, { useState, useEffect } from 'react';  
  2.   
  3. const AddOrEditStudent= (props) => {  
  4.     const initialFieldValues = {  
  5.         FullName: '',  
  6.         RollNo: '',  
  7.         Subject: '',  
  8.         Class: ''  
  9.     }  
  10.   
  11.     var [values, setValues] = useState(initialFieldValues)  

  12.     useEffect(() => {  
  13.         if (props.currentId === '')  
  14.             setValues({ ...initialFieldValues })  
  15.         else  
  16.             setValues({  
  17.                 ...props.studentObjects[props.currentId]  
  18.             })  
  19.     }, [props.currentId, props.studentObjects])  
  20.   
  21.     const handleInputChange = e => {  
  22.         var { name, value } = e.target;  
  23.         setValues({  
  24.             ...values,  
  25.             [name]: value  
  26.         })  
  27.     }  
  28.   
  29.     const handleFormSubmit = e => {  
  30.         e.preventDefault()  
  31.         props.addOrEdit(values);  
  32.     }  
  33.   
  34.     return (  
  35.         <form autoComplete="off" onChange={handleFormSubmit}>  
  36.             <div className="col-12 col-md-12">  
  37.                 <div className="card">  
  38.                     <div className="card-header" >  
  39.                         <input value={props.currentId === "" ? "Add Student Info" : "Update Student Info"} />  
  40.                     </div>  
  41.                     <div className="card-body">  
  42.                         <div className="center-form">  
  43.                             <div className="row">  
  44.                                 <div className="col-12 col-md-6">  
  45.                                     <div className="form-group">  
  46.                                         <label className="col-form-label">Full Name<span  
  47.                                             className="mandatoryFieldColor">*</span></label>  
  48.                                         <input value={values.FullName}  
  49.                                             onChange={handleInputChange} type="text" className="form-control" name="FullName"  
  50.                                         />  
  51.                                     </div>  
  52.                                 </div>  
  53.                                 <div className="col-12 col-md-6">  
  54.                                     <div className="form-group">  
  55.                                         <label className="col-form-label">Roll No<span  
  56.                                             className="mandatoryFieldColor">*</span></label>  
  57.                                         <input value={values.RollNo} onChange={handleInputChange} type="text" className="form-control" name="RollNo"  
  58.                                         />  
  59.                                     </div>  
  60.                                 </div>  
  61.                                 <div className="col-12 col-md-6">  
  62.                                     <div className="form-group">  
  63.                                         <label className="col-form-label">Subject<span  
  64.                                             className="mandatoryFieldColor">*</span></label>  
  65.                                         <input value={values.Subject} onChange={handleInputChange} type="text" className="form-control" name="Subject"  
  66.                                         />  
  67.                                     </div>  
  68.                                 </div>  
  69.                                 <div className="col-12 col-md-6">  
  70.                                     <div className="form-group">  
  71.                                         <label className="col-form-label">Class<span  
  72.                                             className="mandatoryFieldColor">*</span></label>  
  73.                                         <input value={values.Class} onChange={handleInputChange} type="text" className="form-control" name="Class"  
  74.                                         />  
  75.                                     </div>  
  76.                                 </div>  
  77.                                 <div className="col-12 col-md-12">  
  78.                                     <div className="btn-group mb-3 mt-2 cmn-btn-grp">  
  79.                                         <input type="submit" value={props.currentId === "" ? "Save" : "Update"} className="btn btn-success btn-block" />  
  80.                                     </div>  
  81.                                 </div>  
  82.                             </div>  
  83.                         </div>  
  84.                     </div>  
  85.                 </div>  
  86.             </div>  
  87.         </form>  
  88.     );  
  89. }  
  90.   
  91. export default AddOrEditStudent;  
How To Implement React CRUD Using Firebase
 
The form is divided into components, addEditStudent component to store the records, and studentInfo component for displaying the records. 
 
How To Implement React CRUD Using Firebase
 
Step 10
 
For styling purposes we are including a file which is app.css. Create the file and paste the below code.
  1. .App { 
  2.   text-align: center; 
  3. }  
  4.   
  5. .App-logo { 
  6.   height: 40vmin; 
  7.   pointer-events: none; 
  8. }  
  9.   
  10. @media (prefers-reduced-motion: no-preference) { 
  11.   .App-logo { 
  12.     animation: App-logo-spin infinite 20s linear; 
  13.   }  
  14. }  
  15.   
  16. .App-header { 
  17.   background-color: #282c34; 
  18.   min-height: 100vh; 
  19.   display: flex; 
  20.   flex-direction: column; 
  21.   align-items: center; 
  22.   justify-content: center; 
  23.   font-size: calc(10px + 2vmin); 
  24.   color: white; 
  25. }  
  26.   
  27. .App-link { 
  28.   color: #61dafb; 
  29. }  
  30.   
  31. @keyframes App-logo-spin { 
  32.   from { 
  33.     transform: rotate(0deg); 
  34.   }  
  35.   to { 
  36.     transform: rotate(360deg); 
  37.   }  
  38. }  
Now we are done with our coding part and it's time for the output. On the terminal type npm start to compile and run in our browser. So go to localhost:3000 and hit enter .

How To Implement React CRUD Using Firebase
 

Conclusion

 
In this article, we have seen how to perform CRUD operations in Reactjs.
 
Please give your valuable feedback/comments/questions about this article.