Introduction
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.
- 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.
- npm install bootstrap
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 .
Open your browser then go to Google Firebase Console and log in using your Google account.

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 = {
- /*
- replace this object with yours
- */
- 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"
- };
- // Initialize Firebase
- 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;

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 {
- text-align: center;
- }
- .App-logo {
- height: 40vmin;
- pointer-events: none;
- }
- @media (prefers-reduced-motion: no-preference) {
- .App-logo {
- animation: App-logo-spin infinite 20s linear;
- }
- }
- .App-header {
- background-color: #282c34;
- min-height: 100vh;
- display: flex;
- flex-direction: column;
- align-items: center;
- justify-content: center;
- font-size: calc(10px + 2vmin);
- color: white;
- }
- .App-link {
- color: #61dafb;
- }
- @keyframes App-logo-spin {
- from {
- transform: rotate(0deg);
- }
- to {
- transform: rotate(360deg);
- }
- }
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.

Hanis IbrPosted Oct 16, 2021, 5:38 AM
Hi, i tried to run it but got an error saying that default.child is not a function. The error was originated from the code for fetching the created data from the firestore database.
scott skiltonPosted Mar 9, 2021, 5:57 PM
Hi. I implemented this (Very good so far - thanks), but I cannot edit the values in the input text boxes...it simply will not let me. Tried with Chrome and Edge. Any ideas please? Thanks.
swapnil rajPosted Mar 2, 2021, 8:58 AM
Hello Siddharth, I am getting problem Edit and Delete record. On Edit click unable to set data to textboxes. I am using "firebase": "^8.2.9" "react": "^16.13.1",
Javier ArrPosted Feb 11, 2021, 3:29 AM
Siddharth hello, thanks for your response. So in the addoreditstudent.js page, that where i assume we're supposed to push to the db. but you never connect it, i am not able to push to my firebase, any solutions will be greatly appreciated
Javier ArrPosted Feb 9, 2021, 11:33 PM
Thank you for sharing, found it very helpful. However I am also having troubles creating a new student?
ankit pandeyPosted Jan 7, 2021, 2:10 AM
Hi, thanks for sharing. I have used your code but I am unable to add a new record. looks like i missing anything <input value={values.RollNo} onChange={handleInputChange} type="text" className="form-control" />