Creating a simple CRUD application with React and Express

Creating a Simple CRUD Application with React and Express

In the world of web development, the ability to create a CRUD application is fundamental. CRUD stands for Create, Read, Update, and Delete - the four basic functions that allow you to manage data effectively. In this article, we'll walk through building a simple CRUD application using React for the front end and Express for the back end. This combination leverages the power of JavaScript on both the client and server sides, making it a popular choice among developers.

What is a CRUD Application?

A CRUD application is a software application that allows users to perform the four basic operations on data. Here’s a brief overview of each operation:

  • Create: Adding new data entries.
  • Read: Retrieving existing data entries.
  • Update: Modifying existing data entries.
  • Delete: Removing data entries.

Use Cases for CRUD Applications

CRUD applications are widely used in various scenarios, including:

  • Content Management Systems (CMS): Managing articles, images, and other media.
  • E-commerce Platforms: Handling products, orders, and customer information.
  • Database Management Tools: Interfacing with databases to manage records.

With an understanding of CRUD operations and their applications, let's dive into the implementation.

Setting Up the Environment

Before we start coding, we need to set up our project environment. You'll need Node.js and npm (Node Package Manager) installed on your machine. Once you have those, follow these steps:

  1. Create a new directory for your project:

bash mkdir react-express-crud cd react-express-crud

  1. Initialize a Node.js project:

bash npm init -y

  1. Install Express and CORS:

bash npm install express cors

  1. Set up React:

In a new terminal, navigate to your project directory and run:

bash npx create-react-app client

  1. Install Axios in the React app:

bash cd client npm install axios

Now, you have a basic setup for your CRUD application.

Building the Express Back End

Create the Server

In the root of your project (where your package.json file is located), create a new file named server.js. This file will configure your Express server.

const express = require('express');
const cors = require('cors');
const app = express();
const PORT = 5000;

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

let items = [];

// CRUD Operations
app.get('/api/items', (req, res) => {
    res.json(items);
});

app.post('/api/items', (req, res) => {
    const newItem = req.body;
    items.push(newItem);
    res.status(201).json(newItem);
});

app.put('/api/items/:id', (req, res) => {
    const { id } = req.params;
    const updatedItem = req.body;
    items[id] = updatedItem;
    res.json(updatedItem);
});

app.delete('/api/items/:id', (req, res) => {
    const { id } = req.params;
    items.splice(id, 1);
    res.status(204).send();
});

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

Explanation of the Code

  • Middleware: We use CORS to enable cross-origin requests and express.json() to parse JSON data.
  • CRUD Endpoints:
  • GET /api/items: Retrieves all items.
  • POST /api/items: Adds a new item.
  • PUT /api/items/:id: Updates an existing item.
  • DELETE /api/items/:id: Deletes an item.

Building the React Front End

Now that we have our back end set up, let’s create the React components.

Create the CRUD Component

In the client/src directory, create a new file named CrudApp.js. This will handle the user interface and interactions.

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

const CrudApp = () => {
    const [items, setItems] = useState([]);
    const [item, setItem] = useState({ name: '' });
    const [editIndex, setEditIndex] = useState(null);

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

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

    const handleChange = (e) => {
        setItem({ ...item, [e.target.name]: e.target.value });
    };

    const handleSubmit = async (e) => {
        e.preventDefault();
        if (editIndex !== null) {
            await axios.put(`http://localhost:5000/api/items/${editIndex}`, item);
        } else {
            await axios.post('http://localhost:5000/api/items', item);
        }
        setItem({ name: '' });
        setEditIndex(null);
        fetchItems();
    };

    const handleEdit = (index) => {
        setItem(items[index]);
        setEditIndex(index);
    };

    const handleDelete = async (index) => {
        await axios.delete(`http://localhost:5000/api/items/${index}`);
        fetchItems();
    };

    return (
        <div>
            <h1>CRUD Application</h1>
            <form onSubmit={handleSubmit}>
                <input
                    type="text"
                    name="name"
                    value={item.name}
                    onChange={handleChange}
                    required
                />
                <button type="submit">{editIndex !== null ? 'Update' : 'Add'}</button>
            </form>
            <ul>
                {items.map((item, index) => (
                    <li key={index}>
                        {item.name}
                        <button onClick={() => handleEdit(index)}>Edit</button>
                        <button onClick={() => handleDelete(index)}>Delete</button>
                    </li>
                ))}
            </ul>
        </div>
    );
};

export default CrudApp;

Explanation of the React Component

  • State Management: We use useState to manage the list of items, the current item being edited, and the index of the item being edited.
  • Fetching Data: The fetchItems function retrieves data from the Express server.
  • Handling Input: The handleChange function updates the state as the user types.
  • Submitting Data: The handleSubmit function adds or updates items based on the editIndex.
  • Edit and Delete Functions: These functions allow users to modify or remove items from the list.

Rendering the Component

Finally, update the client/src/App.js file to include the CrudApp component:

import React from 'react';
import CrudApp from './CrudApp';

function App() {
    return (
        <div className="App">
            <CrudApp />
        </div>
    );
}

export default App;

Running the Application

To run your application, follow these steps:

  1. Start the Express server:

bash node server.js

  1. Start the React application:

bash cd client npm start

Your CRUD application should now be up and running! Navigate to http://localhost:3000, where you can create, read, update, and delete items.

Conclusion

Creating a simple CRUD application with React and Express provides a solid foundation in both front-end and back-end development. This tutorial has guided you through setting up your environment, building the server and client, and implementing the necessary functionality.

As you continue to develop your skills, consider exploring database integration, authentication, and state management libraries like Redux to further enhance your applications. 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.