CRUD Operation with React.js and Firebase

watch_later 01 March, 2023

React.js is a popular front-end library used for building dynamic and interactive user interfaces. It is widely used in web development due to its simplicity, flexibility, and high performance. One of the essential operations in web development is CRUD (Create, Read, Update, Delete). In this article, we will explore the CRUD operations in React.js with a simple example of an e-commerce system.

Step-by-Step Tutorial: Creating a E-commerce System with React.js and Firebase Database

E-commerce System Example:

To illustrate the CRUD operations in React.js, we will use a simple e-commerce system example. The system will have the following entities:

  • Products: contains product information such as name, price, and description.
  • Categories: categorizes the products according to their types.
  • Orders: records the orders made by customers, including the products and quantities.

We will create a web application that allows the admin user to perform CRUD operations on these entities, including adding, editing, deleting, and viewing them.

Step-by-Step Guide:

1. Project and Database Setup

The first step is to create a new React.js project and name it "codingvila". You can use the create-react-app CLI tool to create a new React.js project. Once you have created the project, install the Firebase SDK to connect your React.js application to the Firebase database. You can install the Firebase SDK by running the following command in the terminal:

npm install firebase

After installing the Firebase SDK, create a new Firebase project and configure it to work with your React.js project. You can follow the Firebase documentation for detailed instructions on how to create a new project and configure it.

2. Creating Components

Next, we will create separate components for each entity in our e-commerce system. For example, we will create ProductList, CategoryList, and OrderList components to display the list of products, categories, and orders, respectively. Similarly, we will create ProductForm, CategoryForm, and OrderForm components to add or edit the entities.

Let's take the ProductList component as an example. Here is the code for the ProductList component:

import React, { useState, useEffect } from 'react';
import firebase from 'firebase/app';
import 'firebase/firestore';
 
const ProductList = () => {
    const [products, setProducts] = useState([]);
 
    useEffect(() => {
        const fetchData = async () => {
            const db = firebase.firestore();
            const data = await db.collection('products').get();
            setProducts(data.docs.map(doc => ({ ...doc.data(), id: doc.id })));
        };
        fetchData();
    }, []);
 
    return (
        <div>
            <h2>Product List</h2>
            <table>
                <thead>
                    <tr>
                        <th>Name</th>
                        <th>Price</th>
                        <th>Description</th>
                    </tr>
                </thead>
                <tbody>
                    {products.map(product => (
                        <tr key={product.id}>
                            <td>{product.name}</td>
                            <td>{product.price}</td>
                            <td>{product.description}</td>
                        </tr>
                    ))}
                </tbody>
            </table>
        </div>
    );
};
 
export default ProductList;

In this code, we have defined the ProductList component as a functional component. We have used the useState hook to define the state variable for the list of products, and the useEffect hook to fetch the products from the Firebase database when the component mounts.

Inside the useEffect hook, we have defined the fetchData function to fetch the products from the Firebase database. We have used the Firebase SDK to get a reference to the 'products' collection in the firebase database, and then used the get() method to fetch the documents from the collection. Once we have fetched the documents, we used the map() method to transform the documents into a format that is easier to render in the component. Finally, we have updated the state variable products with the transformed data.

In the render method, we have used the map() method to loop through the products array and render each product as a table row. We have also added a header row to display the column names.

3. Implementing CRUD Operations

Next, we will implement the CRUD operations for each entity in our e-commerce system. We will use the Firebase SDK to perform the CRUD operations on the Firebase database.

Here is an example of adding a new product to the Firebase database:

import React, { useState } from 'react';
import firebase from 'firebase/app';
import 'firebase/firestore';
 
const ProductForm = () => {
    const [name, setName] = useState('');
    const [price, setPrice] = useState('');
    const [description, setDescription] = useState('');
 
    const handleSubmit = async (e) => {
        e.preventDefault();
        const db = firebase.firestore();
        await db.collection('products').add({
            name,
            price,
            description,
        });
        setName('');
        setPrice('');
        setDescription('');
    };
 
    return (
        <form onSubmit={handleSubmit}>
            <input type="text" value={name} onChange={(e) => setName(e.target.value)} placeholder="Product Name" />
            <input type="number" value={price} onChange={(e) => setPrice(e.target.value)} placeholder="Product Price" />
            <textarea value={description} onChange={(e) => setDescription(e.target.value)} placeholder="Product Description" />
            <button type="submit">Add Product</button>
        </form>
    );
};
 
export default ProductForm;

In this code, we have defined the ProductForm component as a functional component. We have used the useState hook to define the state variables for the name, price, and description of the product.

In the handleSubmit method, we have defined a function to handle the form submission. We have used the Firebase SDK to get a reference to the 'products' collection in the Firebase database, and then used the add() method to add a new document to the collection with the name, price, and description of the product.

After adding the new product to the database, we reset the state variables to clear the input fields.

4. Rendering Components

Finally, we will render the components in the main App component. We will use React Router to navigate between different pages of the e-commerce system, including the product list, product form, category list, category form, order list, and order form.

Here is an example of rendering the ProductList and ProductForm components using React Router:

import React from 'react';
import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom';
import ProductList from './ProductList';
import ProductForm from './ProductForm';
 
const App = () => {
    return (
        <Router>
            <div>
                <nav>
                    <ul>
                        <li>
                            <Link to="/">Product List</Link>
                        </li>
                        <li>
                            <Link to="/add-product">Add Product</Link>
                        </li>
                    </ul>
                </nav>
 
                <Switch>
                    <Route path="/add-product">
                        <ProductForm />
                    </Route>
                    <Route path="/">
                        <ProductList />
                    </Route>
                </Switch>
            </div>
        </Router>
    );
};
 
export default App;

In this code, we have defined the main App component as a functional component. We have imported the ProductList and ProductForm components and used the React Router to define the routes for each component.

In the navigation bar, we have defined two links to navigate to the ProductList and ProductForm components. We have used the Link component from React Router to create clickable links.

In the Switch component, we have defined the routes for each component. The Route component is used to define the URL path for each component. The path prop is used to define the URL path, and the component to render is defined as a child component of the Route component.

When the user clicks on a link in the navigation bar, the React Router will match the URL path to the defined routes and render the corresponding component.

Tags:

  • react-firebase crud github
  • react firebase realtime database example
  • firebase crud operations
  • firebase crud operations javascript
  • firebase react example
  • firestore crud operations react
  • firebase firestore crud
  • firebase react example github
  • can i use firebase with react js
  • crud operation with react.js
  • how do you do crud operations in react
  • what is crud operation in js
  • what is rest api crud operations
  • how do you call api in react js
  • how do i create a rest api for crud
  • can you do crud with javascript
  • react js crud example step by step
  • react js crud example with rest api
  • react js crud example with json file
  • react js crud example github
  • react crud example with hooks
  • crud operations in react js with axios
  • how do you use crud in react js
  • what is crud explain crud with example
  • how do you do crud operations in api

Conclusion

In this tutorial, we have learned how to implement the CRUD operations on React.js using the Firebase database. We have also learned how to create a simple e-commerce system with React.js, including the ProductList, ProductForm, CategoryList, CategoryForm, OrderList, and OrderForm components.

By following the step-by-step guide, you can create your own e-commerce system with React.js and Firebase database. You can also customize the system to fit your own business needs, and add additional features such as payment integration, shipping management, and user authentication.

I hope that this tutorial has been helpful in getting you started with React.js and Firebase database, and I wish you success in your web development projects!

Codingvila provides articles and blogs on web and software development for beginners as well as free Academic projects for final year students in Asp.Net, MVC, C#, Vb.Net, SQL Server, Angular Js, Android, PHP, Java, Python, Desktop Software Application and etc.

Thank you for your valuable time, to read this article, If you like this article, please share this article and post your valuable comments.

Once, you post your comment, we will review your posted comment and publish it. It may take a time around 24 business working hours.

Sometimes I not able to give detailed level explanation for your questions or comments, if you want detailed explanation, your can mansion your contact email id along with your question or you can do select given checkbox "Notify me" the time of write comment. So we can drop mail to you.

If you have any questions regarding this article/blog you can contact us on info.codingvila@gmail.com

sentiment_satisfied Emoticon