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
- To-Do Lists: Manage tasks and keep track of completed items.
- User Management Systems: Administer user data, roles, and permissions.
- Inventory Management: Monitor stock levels and product information.
- 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
- Create a new directory for your project and navigate into it:
bash
mkdir react-node-crud
cd react-node-crud
- Initialize a new Node.js application:
bash
npm init -y
- Install the required packages:
bash
npm install express mongoose cors body-parser
- 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
- Create a React application in a new folder:
bash
npx create-react-app client
cd client
- Install Axios:
bash
npm install axios
- Create the CRUD components. In the
src
directory, create a folder namedcomponents
and addItemForm.js
andItemList.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
- Start the Node.js server:
bash
node server.js
- 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
- CORS Errors: Ensure CORS is enabled in your Express app with
app.use(cors())
. - MongoDB Connection Issues: Check if MongoDB is running on your local machine.
- 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!