make a project for todo app using MERN
- User
make a project for todo app using MERN
- Assistant
make a project for todo app using MERN
Sure! Building a Todo app using the MERN stack (MongoDB, Express.js, React, Node.js) is a great way to understand how full-stack web development works. Below is a step-by-step guide to help you create a Todo application with CRUD (Create, Read, Update, Delete) functionality.
Before you begin, ensure you have the following installed:
Create a directory for your project and navigate into it:
mkdir mern-todo-app
cd mern-todo-app
Initialize a Git repository:
git init
Create a directory for the backend and initialize npm:
mkdir backend
cd backend
npm init -y
Install backend dependencies:
npm install express mongoose cors dotenv
Install dev dependencies:
npm install --save-dev nodemon
Update package.json to use nodemon:
// package.json
"scripts": {
"start": "node server.js",
"dev": "nodemon server.js"
}
In the backend directory, create a server.js file:
touch server.js
Add the following code to set up the server:
// server.js
const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');
require('dotenv').config();
// Create Express app
const app = express();
// Middleware
app.use(cors());
app.use(express.json());
// Start the server
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
console.log(`Server is running on port: ${PORT}`);
});
Create a .env file in the backend directory to store environment variables:
MONGODB_URI=mongodb://localhost:27017/mern-todo
Add MongoDB connection in server.js:
// server.js (continued)
// Connect to MongoDB
mongoose
.connect(process.env.MONGODB_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => console.log('Connected to MongoDB successfully'))
.catch((err) => console.error('MongoDB connection error:', err));
Create a models directory and add todo.model.js:
mkdir models
cd models
touch todo.model.js
Define the Todo schema:
// models/todo.model.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const todoSchema = new Schema(
{
title: { type: String, required: true },
completed: { type: Boolean, default: false },
},
{
timestamps: true,
}
);
const Todo = mongoose.model('Todo', todoSchema);
module.exports = Todo;
Create a routes directory and add todos.js:
cd ..
mkdir routes
cd routes
touch todos.js
Set up the routes in todos.js:
// routes/todos.js
const router = require('express').Router();
let Todo = require('../models/todo.model');
// Get all todos
router.route('/').get((req, res) => {
Todo.find()
.then((todos) => res.json(todos))
.catch((err) => res.status(400).json('Error: ' + err));
});
// Add a new todo
router.route('/add').post((req, res) => {
const title = req.body.title;
const newTodo = new Todo({ title });
newTodo
.save()
.then(() => res.json('Todo added!'))
.catch((err) => res.status(400).json('Error: ' + err));
});
// Update a todo
router.route('/update/:id').post((req, res) => {
Todo.findById(req.params.id)
.then((todo) => {
todo.title = req.body.title;
todo.completed = req.body.completed;
todo
.save()
.then(() => res.json('Todo updated!'))
.catch((err) => res.status(400).json('Error: ' + err));
})
.catch((err) => res.status(400).json('Error: ' + err));
});
// Delete a todo
router.route('/:id').delete((req, res) => {
Todo.findByIdAndDelete(req.params.id)
.then(() => res.json('Todo deleted.'))
.catch((err) => res.status(400).json('Error: ' + err));
});
module.exports = router;
Import and use the routes in server.js:
// server.js (continued)
const todosRouter = require('./routes/todos');
app.use('/todos', todosRouter);
Navigate back to the root project directory:
cd ../../
Create the React app using create-react-app:
npx create-react-app frontend
Navigate into the frontend directory:
cd frontend
Start the React app:
npm start
This should open http://localhost:3000 in your browser with the default React welcome page.
We'll create components to interact with our backend API.
Delete unnecessary files:
rm src/App.test.js src/index.css src/logo.svg
Update src/index.js to remove references to deleted files:
// src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
ReactDOM.render(<App />, document.getElementById('root'));
Update src/App.js:
// src/App.js
import React from 'react';
import { BrowserRouter as Router, Route } from 'react-router-dom';
import TodoList from './components/TodoList';
import EditTodo from './components/EditTodo';
import CreateTodo from './components/CreateTodo';
function App() {
return (
<Router>
<div className="container">
<h2>MERN Todo App</h2>
<Route path="/" exact component={TodoList} />
<Route path="/edit/:id" component={EditTodo} />
<Route path="/create" component={CreateTodo} />
</div>
</Router>
);
}
export default App;
Install necessary packages:
npm install axios react-router-dom
Create a components directory:
mkdir src/components
Create TodoList.js:
// src/components/TodoList.js
import React, { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import axios from 'axios';
function TodoList() {
const [todos, setTodos] = useState([]);
useEffect(() => {
axios
.get('/todos/')
.then((response) => {
setTodos(response.data);
})
.catch((error) => {
console.log(error);
});
}, []);
const deleteTodo = (id) => {
axios.delete('/todos/' + id).then((response) => {
console.log(response.data);
});
setTodos(todos.filter((el) => el._id !== id));
};
return (
<div>
<h3>Todos List</h3>
<table className="table">
<thead>
<tr>
<th>Title</th>
<th>Completed</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{todos.map((currentTodo) => (
<tr key={currentTodo._id}>
<td>{currentTodo.title}</td>
<td>{currentTodo.completed ? 'Yes' : 'No'}</td>
<td>
<Link to={'/edit/' + currentTodo._id}>Edit</Link> |{' '}
<a
href="# "
onClick={() => {
deleteTodo(currentTodo._id);
}}
>
Delete
</a>
</td>
</tr>
))}
</tbody>
</table>
</div>
);
}
export default TodoList;
Create CreateTodo.js:
// src/components/CreateTodo.js
import React, { useState } from 'react';
import axios from 'axios';
function CreateTodo(props) {
const [title, setTitle] = useState('');
const onSubmit = (e) => {
e.preventDefault();
const newTodo = {
title: title,
};
axios
.post('/todos/add', newTodo)
.then((res) => console.log(res.data));
setTitle('');
props.history.push('/');
};
return (
<div>
<h3>Create New Todo</h3>
<form onSubmit={onSubmit}>
<div className="form-group">
<label>Title: </label>
<input
type="text"
required
className="form-control"
value={title}
onChange={(e) => {
setTitle(e.target.value);
}}
/>
</div>
<div className="form-group">
<input type="submit" value="Create Todo" className="btn btn-primary" />
</div>
</form>
</div>
);
}
export default CreateTodo;
Create EditTodo.js:
// src/components/EditTodo.js
import React, { useState, useEffect } from 'react';
import axios from 'axios';
function EditTodo(props) {
const [title, setTitle] = useState('');
const [completed, setCompleted] = useState(false);
useEffect(() => {
axios
.get('/todos/' + props.match.params.id)
.then((response) => {
setTitle(response.data.title);
setCompleted(response.data.completed);
})
.catch((error) => {
console.log(error);
});
}, [props.match.params.id]);
const onSubmit = (e) => {
e.preventDefault();
const updatedTodo = {
title: title,
completed: completed,
};
axios
.post('/todos/update/' + props.match.params.id, updatedTodo)
.then((res) => console.log(res.data));
props.history.push('/');
};
return (
<div>
<h3>Edit Todo</h3>
<form onSubmit={onSubmit}>
<div className="form-group">
<label>Title: </label>
<input
type="text"
required
className="form-control"
value={title}
onChange={(e) => {
setTitle(e.target.value);
}}
/>
</div>
<div className="form-group">
<label>Completed: </label>
<input
type="checkbox"
checked={completed}
onChange={(e) => {
setCompleted(e.target.checked);
}}
/>
</div>
<div className="form-group">
<input type="submit" value="Update Todo" className="btn btn-primary" />
</div>
</form>
</div>
);
}
export default EditTodo;
To avoid CORS issues, you can set up a proxy in the frontend/package.json:
// frontend/package.json
"proxy": "http://localhost:5000",
This will proxy any unrecognized API requests from the React app to the backend server.
Alternatively, use full URLs in your axios requests and ensure CORS is properly set up on the server.
You can use Bootstrap or any other CSS framework for styling.
Install Bootstrap:
npm install bootstrap
Import Bootstrap in src/index.js:
// src/index.js (continued)
import 'bootstrap/dist/css/bootstrap.min.css';
Start the backend server:
cd backend
npm run dev
Start the frontend app in another terminal window:
cd frontend
npm start
Now, you should be able to interact with your Todo app at http://localhost:3000.
Congratulations! You've built a full-stack Todo application using the MERN stack. You can now:
Next Steps:
Resources:
Feel free to ask if you have any questions or need further assistance!
Not yet included in a published release.