Creating a Simple CRUD Application with React and Node.js
In today’s tech landscape, mastering full-stack development is essential for web developers. One of the most effective ways to build dynamic web applications is through the combination of React for the frontend and Node.js for the backend. In this article, we’ll guide you through creating a simple CRUD (Create, Read, Update, Delete) application using these powerful tools.
What is CRUD?
CRUD stands for Create, Read, Update, and Delete. It represents the four basic operations we can perform on data in applications. Here’s a quick breakdown:
- Create: Adding new data to the application.
- Read: Retrieving existing data from the application.
- Update: Modifying existing data.
- Delete: Removing data from the application.
CRUD applications are ubiquitous; from simple to-do lists to complex content management systems, they form the backbone of many web services.
Prerequisites
Before we dive into coding, ensure you have the following installed on your machine:
- Node.js and npm (Node Package Manager)
- A code editor (e.g., VSCode)
- Basic knowledge of JavaScript and React
Setting Up the Project
Step 1: Initialize the Node.js Backend
- Create a new directory for your project:
bash
mkdir react-node-crud
cd react-node-crud
- Set up the Node.js server:
bash
mkdir server
cd server
npm init -y
npm install express mongoose cors body-parser
- express: A web framework for Node.js.
- mongoose: An ODM (Object Data Modeling) library for MongoDB.
- cors: A package to enable CORS (Cross-Origin Resource Sharing).
-
body-parser: Middleware to parse incoming request bodies.
-
Create a simple server:
In the server
directory, create 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 = process.env.PORT || 5000;
app.use(cors()); app.use(bodyParser.json());
mongoose.connect('mongodb://localhost:27017/crudDB', { useNewUrlParser: true, useUnifiedTopology: true });
const itemSchema = new mongoose.Schema({ name: String, });
const Item = mongoose.model('Item', itemSchema);
// CRUD endpoints app.post('/items', async (req, res) => { const newItem = new Item(req.body); await newItem.save(); res.status(201).send(newItem); });
app.get('/items', async (req, res) => { const items = await Item.find(); res.status(200).send(items); });
app.put('/items/:id', async (req, res) => { const updatedItem = await Item.findByIdAndUpdate(req.params.id, req.body, { new: true }); res.status(200).send(updatedItem); });
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}
);
});
```
Step 2: Set Up the React Frontend
- Navigate back to the root directory and create the React app:
bash
cd ..
npx create-react-app client
cd client
npm install axios
-
axios: A promise-based HTTP client for making requests to our Node.js backend.
-
Building the React components:
Replace the contents of src/App.js
with the following code:
```javascript import React, { useState, useEffect } from 'react'; import axios from 'axios';
function App() { const [items, setItems] = useState([]); const [name, setName] = useState(''); const [editId, setEditId] = useState(null);
const fetchItems = async () => {
const response = await axios.get('http://localhost:5000/items');
setItems(response.data);
};
useEffect(() => {
fetchItems();
}, []);
const addItem = async () => {
const response = await axios.post('http://localhost:5000/items', { name });
setItems([...items, response.data]);
setName('');
};
const updateItem = async () => {
const response = await axios.put(`http://localhost:5000/items/${editId}`, { name });
setItems(items.map(item => (item._id === editId ? response.data : item)));
setName('');
setEditId(null);
};
const deleteItem = async (id) => {
await axios.delete(`http://localhost:5000/items/${id}`);
setItems(items.filter(item => item._id !== id));
};
return (
<div>
<h1>CRUD Application</h1>
<input
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="Enter item name"
/>
{editId ? (
<button onClick={updateItem}>Update Item</button>
) : (
<button onClick={addItem}>Add Item</button>
)}
<ul>
{items.map(item => (
<li key={item._id}>
{item.name}
<button onClick={() => { setEditId(item._id); setName(item.name); }}>Edit</button>
<button onClick={() => deleteItem(item._id)}>Delete</button>
</li>
))}
</ul>
</div>
);
}
export default App; ```
Step 3: Running the Application
- Start the Node.js server:
In the server
directory, run:
bash
node server.js
- Start the React app:
In the client
directory, run:
bash
npm start
Troubleshooting Common Issues
- CORS Errors: If you encounter CORS issues, ensure your server has
cors
middleware set up correctly. - Database Connection Issues: Make sure MongoDB is running on your system. Use
mongod
to start the MongoDB service.
Conclusion
Congratulations! You have successfully created a simple CRUD application using React and Node.js. This project lays the foundation for more complex applications. Now, you can explore additional features like user authentication, pagination, or integrating a UI framework like Bootstrap for better styling.
By mastering CRUD operations, you can enhance your full-stack development skills and create applications that effectively manage data. Keep experimenting and building, and you'll soon be well on your way to becoming a proficient developer!