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

Building a CRUD Application with React and Express

In the world of web development, creating a CRUD (Create, Read, Update, Delete) application is a foundational project that helps developers grasp the essential concepts of data manipulation. The combination of React for the frontend and Express for the backend creates a powerful stack for building dynamic web applications. In this article, we will walk through the process of building a simple CRUD application using React and Express, complete with code examples and actionable insights.

What is CRUD?

CRUD stands for the four basic operations of persistent storage:

  • Create: Adding new data to the database.
  • Read: Retrieving data from the database.
  • Update: Modifying existing data.
  • Delete: Removing data from the database.

CRUD applications are fundamental in various real-world scenarios, such as managing products in an e-commerce site or handling user data in a social network.

Why Use React and Express?

  • React: A JavaScript library for building user interfaces, especially single-page applications. Its component-based architecture promotes reusability and maintainability of code.

  • Express: A minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications. It’s particularly suitable for building RESTful APIs.

Use Cases for CRUD Applications

  • Task Management Systems: Allowing users to manage their to-do lists.
  • Inventory Systems: Tracking products and their quantities.
  • User Profiles: Enabling users to create and manage their profiles.

Setting Up the Environment

Before we dive into coding, ensure you have the following tools installed:

  • Node.js: Ensure you have Node.js installed; this will allow you to use npm (Node Package Manager).
  • Create React App: A comfortable way to set up a React project.

Step 1: Create a New React App

Run the following command in your terminal:

npx create-react-app crud-app
cd crud-app

Step 2: Set Up Express Server

Navigate to your project directory and create a new folder for the server:

mkdir server
cd server
npm init -y
npm install express cors mongoose
  • Cors: Middleware to enable CORS (Cross-Origin Resource Sharing) in your Express application.
  • Mongoose: A MongoDB object modeling tool that provides a schema-based solution to model your application data.

Step 3: Create the Express Server

Create a file named server.js in the server folder and add the following code:

const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');

const app = express();
const PORT = process.env.PORT || 5000;

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

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

// Define a simple schema
const ItemSchema = new mongoose.Schema({
    name: String,
});

const Item = mongoose.model('Item', ItemSchema);

// CRUD routes
app.post('/items', async (req, res) => {
    const newItem = new Item(req.body);
    await newItem.save();
    res.json(newItem);
});

app.get('/items', async (req, res) => {
    const items = await Item.find();
    res.json(items);
});

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

app.delete('/items/:id', async (req, res) => {
    await Item.findByIdAndDelete(req.params.id);
    res.json({ message: 'Item deleted' });
});

app.listen(PORT, () => {
    console.log(`Server running on port ${PORT}`);
});

Step 4: Build the Frontend with React

Now let's go back to the React application. Open the src/App.js file and replace its content with the following code:

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

const App = () => {
    const [items, setItems] = useState([]);
    const [newItem, setNewItem] = useState('');

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

    const addItem = async () => {
        const res = await axios.post('http://localhost:5000/items', { name: newItem });
        setItems([...items, res.data]);
        setNewItem('');
    };

    const updateItem = async (id) => {
        const updatedName = prompt('Enter new name:');
        const res = await axios.put(`http://localhost:5000/items/${id}`, { name: updatedName });
        setItems(items.map(item => (item._id === id ? res.data : item)));
    };

    const deleteItem = async (id) => {
        await axios.delete(`http://localhost:5000/items/${id}`);
        setItems(items.filter(item => item._id !== id));
    };

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

    return (
        <div>
            <h1>CRUD Application</h1>
            <input
                type="text"
                value={newItem}
                onChange={(e) => setNewItem(e.target.value)}
                placeholder="Add a new item"
            />
            <button onClick={addItem}>Add Item</button>
            <ul>
                {items.map(item => (
                    <li key={item._id}>
                        {item.name}
                        <button onClick={() => updateItem(item._id)}>Update</button>
                        <button onClick={() => deleteItem(item._id)}>Delete</button>
                    </li>
                ))}
            </ul>
        </div>
    );
};

export default App;

Step 5: Running the Application

  1. Start your Express server: bash node server.js

  2. In another terminal, navigate to your React app folder and start the React application: bash npm start

Troubleshooting Tips

  • CORS Issues: If you encounter CORS errors, ensure that the Express server is running and that you've added the cors middleware.
  • Database Connection: Make sure MongoDB is running. If you face connection issues, verify your MongoDB URI.
  • React App Not Loading: Check for errors in the console and ensure your API endpoints are correct.

Conclusion

Building a CRUD application with React and Express is a rewarding project that reinforces core web development concepts. By following the steps outlined in this guide, you can create a functional application that allows users to manage data seamlessly. Whether you're looking to enhance your portfolio or deepen your understanding of full-stack development, this project serves as an excellent foundation. 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.