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
The very first step is to create a new React.js project by using the following command.
- npx create-react-app reactcrud_firebase
Step 2
Open the newly created project in Visual Studio code and install React bootstrap in this project by using the following command.
Step 3
Now, open the index.js file and import Bootstrap.
- 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 .
Click the Add Project button, name it and click on Continue button.
Click on Create Project button then wait a few seconds and click on Continue button. You will be redirected to this page.
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.
Next you can see the firebase SDK .
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.
- npm install --save firebase
Step 6
Now create a new file firebase.js and add our configuration code of our firebase.
- import * as firebase from "firebase";
-
- var firebaseConfig = {
-
-
-
- apiKey: "AIzaSyCm54M-FmiVcYqeAofITgVdboAzhIpc0tU",
- authDomain: "reactcrud-d6fad.firebaseapp.com",
- databaseURL: "https://reactcrud-d6fad.firebaseio.com",
- projectId: "reactcrud-d6fad",
- storageBucket: "reactcrud-d6fad.appspot.com",
- messagingSenderId: "666106395244",
- appId: "1:666106395244:web:4eb7684e35149228c23649"
- };
-
-
- var fireDb = firebase.initializeApp(firebaseConfig);
-
- export default fireDb.database().ref();
Step 7
Next, open app.js then replace all codes with the following.
- import React from 'react'
- import './App.css';
- import StudentInfo from './components/studentInfo ';
- function App() {
- return (
- <div className="row">
- <div className="col-md-8 offset-md-2">
- <StudentInfo />
- </div>
- </div>
- )
- }
-
- export default App;
Step 8
Now create a component folder and inside it create a file name studentInfo.js to store student information.
- import React, { useState, useEffect } from 'react';
- import firebaseDb from "../firebase";
- import AddOrEditStudent from './addOrEditStudent';
-
- const StudentInfo= () => {
-
- var [currentId, setCurrentId] = useState('');
- var [studentObjects, setStudentObjects] = useState({})
- useEffect(() => {
- firebaseDb.child('Student').on('value', snapshot => {
- if (snapshot.val() != null) {
- setStudentObjects({
- ...snapshot.val()
- });
- } else{
- setStudentObjects({});
- }
- })
- }, [])
-
-
- const addOrEdit = (obj) => {
- if (currentId === '')
- firebaseDb.child('Student').push(
- obj,
- err => {
- if (err)
- console.log(err)
- else
- setCurrentId('')
- })
- else
- firebaseDb.child(`Student/${currentId}`).set(
- obj,
- err => {
- if (err)
- console.log(err)
- else
- setCurrentId('')
- })
- }
-
- const onDelete = id => {
- if (window.confirm('Are you sure to delete this record?')) {
- firebaseDb.child(`Student/${id}`).remove(
- err => {
- if (err)
- console.log(err)
- else
- setCurrentId('')
- })
- }
- }
-
- return (
- <div className="card">
- <div className="card-body pb-0">
- <div className="card">
- <div className="card-header main-search dash-search">
- <h3>
- Student Information Details
- </h3>
- </div>
- </div>
- <div className="row">
- <AddOrEditStudent {...({ currentId, studentObjects, addOrEdit })}></AddOrEditStudent>
- <div className="col-12 col-md-12">
- <div className="card">
- <div className="card-header">Student Management</div>
- <div className="card-body position-relative">
- <div className="table-responsive cnstr-record product-tbl">
- <table className="table table-bordered heading-hvr">
- <thead>
- <tr>
- <th className="active">Full Name</th>
- <th>Roll No</th>
- <th>Subject</th>
- <th>Class</th>
- <th width="60"> </th>
- <th width="60"> </th>
- </tr>
- </thead>
- <tbody>
- {
- Object.keys(studentObjects).map((key) => (
- <tr key={key}>
- <td>{studentObjects[key].FullName}</td>
- <td>{studentObjects[key].RollNo}</td>
- <td>{studentObjects[key].Subject}</td>
- <td>{studentObjects[key].Class}</td>
-
- <td className="case-record">
- <button type="button" className="btn btn-info"
- onClick={() => { setCurrentId(key) }}>Edit</button>
-
- </td>
- <td> <button type="button" className="btn btn-danger"
- onClick={() => { onDelete(key) }}>Delete</button></td>
- </tr>
- ))
- }
- </tbody>
- </table>
- </div>
- </div>
- </div>
- </div>
- </div>
- </div>
- </div>
- );
- }
-
- 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.
Follow the below code for fetching the created data from the firestore database.
Follow the below code for delete operation. It will remove the records from firebase using .remove() method.
Follow the below code for binding the fetched records in react jsx.
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 .
- import React, { useState, useEffect } from 'react';
-
- const AddOrEditStudent= (props) => {
- const initialFieldValues = {
- FullName: '',
- RollNo: '',
- Subject: '',
- Class: ''
- }
-
- var [values, setValues] = useState(initialFieldValues)
- useEffect(() => {
- if (props.currentId === '')
- setValues({ ...initialFieldValues })
- else
- setValues({
- ...props.studentObjects[props.currentId]
- })
- }, [props.currentId, props.studentObjects])
-
- const handleInputChange = e => {
- var { name, value } = e.target;
- setValues({
- ...values,
- [name]: value
- })
- }
-
- const handleFormSubmit = e => {
- e.preventDefault()
- props.addOrEdit(values);
- }
-
- return (
- <form autoComplete="off" onChange={handleFormSubmit}>
- <div className="col-12 col-md-12">
- <div className="card">
- <div className="card-header" >
- <input value={props.currentId === "" ? "Add Student Info" : "Update Student Info"} />
- </div>
- <div className="card-body">
- <div className="center-form">
- <div className="row">
- <div className="col-12 col-md-6">
- <div className="form-group">
- <label className="col-form-label">Full Name<span
- className="mandatoryFieldColor">*</span></label>
- <input value={values.FullName}
- onChange={handleInputChange} type="text" className="form-control" name="FullName"
- />
- </div>
- </div>
- <div className="col-12 col-md-6">
- <div className="form-group">
- <label className="col-form-label">Roll No<span
- className="mandatoryFieldColor">*</span></label>
- <input value={values.RollNo} onChange={handleInputChange} type="text" className="form-control" name="RollNo"
- />
- </div>
- </div>
- <div className="col-12 col-md-6">
- <div className="form-group">
- <label className="col-form-label">Subject<span
- className="mandatoryFieldColor">*</span></label>
- <input value={values.Subject} onChange={handleInputChange} type="text" className="form-control" name="Subject"
- />
- </div>
- </div>
- <div className="col-12 col-md-6">
- <div className="form-group">
- <label className="col-form-label">Class<span
- className="mandatoryFieldColor">*</span></label>
- <input value={values.Class} onChange={handleInputChange} type="text" className="form-control" name="Class"
- />
- </div>
- </div>
- <div className="col-12 col-md-12">
- <div className="btn-group mb-3 mt-2 cmn-btn-grp">
- <input type="submit" value={props.currentId === "" ? "Save" : "Update"} className="btn btn-success btn-block" />
- </div>
- </div>
- </div>
- </div>
- </div>
- </div>
- </div>
- </form>
- );
- }
-
- export default AddOrEditStudent;
The form is divided into components, addEditStudent component to store the records, and studentInfo component for displaying the records.
Step 10
For styling purposes we are including a file which is app.css. Create the file and paste the below code.
- .App
-
-
-
- .App-logo
-
-
-
-
- @media (prefers-reduced-motion: no-preference)
-
-
-
- }
-
- .App-header
-
-
-
-
-
-
-
-
-
-
- .App-link
-
-
-
- @keyframes App-logo-spin
-
-
-
- to
-
-
- }
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 .
Conclusion
In this article, we have seen how to perform CRUD operations in Reactjs.
Please give your valuable feedback/comments/questions about this article.