building-a-crud-application-with-react-and-nodejs.html

Building a CRUD Application with React and Node.js

Creating a CRUD (Create, Read, Update, Delete) application is one of the best ways to understand the full web development stack. In this article, we will build a simple CRUD application using React for the frontend and Node.js for the backend. This combination offers a powerful framework for developers to create interactive user interfaces and robust server-side applications.

What is a CRUD Application?

A CRUD application allows users to perform basic operations on data. The acronym CRUD stands for:

  • Create: Adding new records
  • Read: Retrieving existing records
  • Update: Modifying existing records
  • Delete: Removing records

CRUD applications are fundamental in web development, serving as the backbone for many projects, such as to-do lists, inventory systems, and user management tools.

Use Cases for CRUD Applications

  1. To-Do Lists: Manage tasks and keep track of completed items.
  2. User Management Systems: Administer user data, roles, and permissions.
  3. Inventory Management: Monitor stock levels and product information.
  4. Content Management Systems (CMS): Create and manage digital content.

Tools and Technologies

To build our CRUD application, we will use:

  • React: A JavaScript library for building user interfaces.
  • Node.js: A JavaScript runtime built on Chrome's V8 JavaScript engine for backend development.
  • Express: A web application framework for Node.js.
  • MongoDB: A NoSQL database for data storage.
  • Axios: A promise-based HTTP client for making requests.

Step-by-Step Guide to Building the CRUD Application

Setting Up the Environment

To get started, ensure you have Node.js and npm installed on your machine. You can verify this by running:

node -v
npm -v

Step 1: Initialize the Node.js Backend

  1. Create a new directory for your project and navigate into it:

bash mkdir react-node-crud cd react-node-crud

  1. Initialize a new Node.js application:

bash npm init -y

  1. Install the required packages:

bash npm install express mongoose cors body-parser

  1. Create a basic server in a file named server.js:

```javascript const express = require('express'); const mongoose = require('mongoose'); const cors = require('cors'); const bodyParser = require('body-parser');

const app = express(); const PORT = 5000;

// Middleware app.use(cors()); app.use(bodyParser.json());

// Connect to MongoDB mongoose.connect('mongodb://localhost:27017/crud-app', { useNewUrlParser: true, useUnifiedTopology: true }) .then(() => console.log('MongoDB connected')) .catch(err => console.error(err));

app.listen(PORT, () => { console.log(Server is running on http://localhost:${PORT}); }); ```

Step 2: Create the MongoDB Model

Create a new folder named models and add a file called Item.js:

const mongoose = require('mongoose');

const ItemSchema = new mongoose.Schema({
   name: { type: String, required: true },
   quantity: { type: Number, required: true }
});

module.exports = mongoose.model('Item', ItemSchema);

Step 3: Build the CRUD API Endpoints

In server.js, add the following routes to handle CRUD operations:

const Item = require('./models/Item');

// Create
app.post('/items', async (req, res) => {
   const newItem = new Item(req.body);
   try {
       const savedItem = await newItem.save();
       res.status(201).json(savedItem);
   } catch (err) {
       res.status(400).json(err);
   }
});

// Read
app.get('/items', async (req, res) => {
   try {
       const items = await Item.find();
       res.status(200).json(items);
   } catch (err) {
       res.status(500).json(err);
   }
});

// Update
app.put('/items/:id', async (req, res) => {
   try {
       const updatedItem = await Item.findByIdAndUpdate(req.params.id, req.body, { new: true });
       res.status(200).json(updatedItem);
   } catch (err) {
       res.status(400).json(err);
   }
});

// Delete
app.delete('/items/:id', async (req, res) => {
   try {
       await Item.findByIdAndDelete(req.params.id);
       res.status(204).json();
   } catch (err) {
       res.status(500).json(err);
   }
});

Step 4: Setting Up the React Frontend

  1. Create a React application in a new folder:

bash npx create-react-app client cd client

  1. Install Axios:

bash npm install axios

  1. Create the CRUD components. In the src directory, create a folder named components and add ItemForm.js and ItemList.js.

ItemForm.js:

import React, { useState } from 'react';
import axios from 'axios';

const ItemForm = ({ refreshItems }) => {
   const [name, setName] = useState('');
   const [quantity, setQuantity] = useState('');

   const handleSubmit = async (e) => {
       e.preventDefault();
       await axios.post('http://localhost:5000/items', { name, quantity });
       refreshItems();
       setName('');
       setQuantity('');
   };

   return (
       <form onSubmit={handleSubmit}>
           <input type="text" value={name} onChange={(e) => setName(e.target.value)} placeholder="Item Name" required />
           <input type="number" value={quantity} onChange={(e) => setQuantity(e.target.value)} placeholder="Quantity" required />
           <button type="submit">Add Item</button>
       </form>
   );
};

export default ItemForm;

ItemList.js:

import React, { useEffect, useState } from 'react';
import axios from 'axios';

const ItemList = () => {
   const [items, setItems] = useState([]);

   const fetchItems = async () => {
       const response = await axios.get('http://localhost:5000/items');
       setItems(response.data);
   };

   useEffect(() => {
       fetchItems();
   }, []);

   return (
       <ul>
           {items.map(item => (
               <li key={item._id}>{item.name} - {item.quantity}</li>
           ))}
       </ul>
   );
};

export default ItemList;

Step 5: Compose the Main Application

In src/App.js, integrate the components:

import React from 'react';
import ItemForm from './components/ItemForm';
import ItemList from './components/ItemList';

const App = () => {
   return (
       <div>
           <h1>CRUD Application</h1>
           <ItemForm />
           <ItemList />
       </div>
   );
};

export default App;

Step 6: Run Your Application

  1. Start the Node.js server:

bash node server.js

  1. In another terminal, navigate to the client directory and start the React app:

bash cd client npm start

Now you can interact with your CRUD application through the browser!

Troubleshooting Common Issues

  1. CORS Errors: Ensure CORS is enabled in your Express app with app.use(cors()).
  2. MongoDB Connection Issues: Check if MongoDB is running on your local machine.
  3. Network Errors: Ensure your API endpoints are correctly defined and reachable from the React application.

Conclusion

Building a CRUD application with React and Node.js provides a solid foundation in full-stack development. By following this guide, you’ve set up a functional application that allows users to create, read, update, and delete items. This knowledge is invaluable as you continue to explore more complex web development projects. Happy coding!

SR
Syed
Rizwan

About the Author

Syed Rizwan is a Machine Learning Engineer with 5 years of experience in AI, IoT, and Industrial Automation.