Creating a CRUD application with React and Express

Creating a CRUD Application with React and Express

Building a CRUD (Create, Read, Update, Delete) application is a great way to learn the fundamentals of full-stack development. In this article, we'll guide you through creating a simple CRUD app using React for the frontend and Express for the backend. This combination allows you to build responsive user interfaces while managing server-side logic efficiently.

What is a CRUD Application?

A CRUD application is a basic software application that allows users to perform four essential operations on data:

  • Create: Add new data entries.
  • Read: Retrieve existing data.
  • Update: Modify existing data.
  • Delete: Remove data entries.

CRUD applications are ubiquitous in web development and serve various purposes, from managing user profiles to handling product inventories.

Tools and Technologies

Frontend: React

React is a popular JavaScript library for building user interfaces, especially single-page applications. It allows developers to create reusable UI components that manage their own state.

Backend: Express

Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications. It simplifies the process of handling HTTP requests and responses.

Database: MongoDB

For this tutorial, we will use MongoDB as our database, which is a NoSQL database that stores data in flexible, JSON-like documents.

Prerequisites

Before you begin, ensure you have the following installed on your machine:

  • Node.js
  • npm (Node Package Manager)
  • MongoDB (or a cloud-based alternative like MongoDB Atlas)

Step-by-Step Guide to Building the CRUD Application

Step 1: Setting Up the Backend with Express

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

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

  1. Create the Server: Initialize a new Node.js application.

bash npm init -y

  1. Install Dependencies: Install Express, Mongoose (to interact with MongoDB), and CORS (to handle cross-origin requests).

bash npm install express mongoose cors

  1. Create the Server File: Create a file named server.js.

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

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

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

mongoose.connect('mongodb://localhost:27017/crudapp', { useNewUrlParser: true, useUnifiedTopology: true, });

const itemSchema = new mongoose.Schema({ name: String, description: String, });

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

// CRUD Routes app.post('/items', async (req, res) => { const item = new Item(req.body); await item.save(); res.status(201).send(item); });

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

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

app.delete('/items/:id', async (req, res) => { await Item.findByIdAndDelete(req.params.id); res.status(204).send(); });

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

  1. Start the Server: Run your server with:

bash node server.js

Step 2: Setting Up the Frontend with React

  1. Create React App: In a new terminal window, create a new React application.

bash npx create-react-app client cd client

  1. Install Axios: We'll use Axios for making HTTP requests.

bash npm install axios

  1. Create Components: In the src directory, create a new folder named components and add a file named ItemManager.js.

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

const ItemManager = () => { const [items, setItems] = useState([]); const [name, setName] = useState(''); const [description, setDescription] = useState(''); const [currentItem, setCurrentItem] = useState(null);

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

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

   const handleSubmit = async (e) => {
       e.preventDefault();
       if (currentItem) {
           await axios.put(`http://localhost:5000/items/${currentItem._id}`, { name, description });
       } else {
           await axios.post('http://localhost:5000/items', { name, description });
       }
       setName('');
       setDescription('');
       setCurrentItem(null);
       fetchItems();
   };

   const handleEdit = (item) => {
       setCurrentItem(item);
       setName(item.name);
       setDescription(item.description);
   };

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

   return (
       <div>
           <h1>Item Manager</h1>
           <form onSubmit={handleSubmit}>
               <input type="text" value={name} onChange={(e) => setName(e.target.value)} placeholder="Name" required />
               <input type="text" value={description} onChange={(e) => setDescription(e.target.value)} placeholder="Description" required />
               <button type="submit">{currentItem ? 'Update' : 'Add'} Item</button>
           </form>
           <ul>
               {items.map(item => (
                   <li key={item._id}>
                       {item.name} - {item.description}
                       <button onClick={() => handleEdit(item)}>Edit</button>
                       <button onClick={() => handleDelete(item._id)}>Delete</button>
                   </li>
               ))}
           </ul>
       </div>
   );

};

export default ItemManager; ```

  1. Integrate the Component: In src/App.js, import and render the ItemManager component.

```javascript import React from 'react'; import ItemManager from './components/ItemManager';

const App = () => { return (

); };

export default App; ```

  1. Run the React App: Start your React application.

bash npm start

Step 3: Testing the Application

At this point, you should have both the backend server and the frontend application running. You can create, read, update, and delete items using the UI. Open your browser and navigate to http://localhost:3000 to see your CRUD application in action.

Troubleshooting Tips

  • CORS Issues: Ensure that your backend server allows requests from your frontend. Use the cors middleware as shown in the server setup.
  • Database Connection: If you encounter issues connecting to MongoDB, check that your MongoDB service is running.
  • React Errors: If your React app doesn't display correctly, check the console for any error messages and ensure your component is rendered correctly.

Conclusion

Creating a CRUD application with React and Express is a rewarding experience that helps you understand the full stack of web development. By following this guide, you have built a simple yet powerful application that encapsulates the core principles of creating, reading, updating, and deleting data. From here, you can expand your application with additional features, styling, or even integrate different databases.

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.