Create a To-Do List App Using MERN Stack Print

  • 0

Create a To-Do List App Using MERN Stack: A Comprehensive Guide

Introduction

Are you looking to build a robust, scalable, and interactive To-Do List application? You've come to the right place! In this comprehensive guide, we'll walk you through each step of creating a To-Do List app using the MERN stack, which includes MongoDB, Express.js, React.js, and Node.js. By the end of this article, you'll have a fully functional app that allows you to add, update, and delete to-do items like a pro.

Prerequisites

Before diving in, let's make sure you have the following tools installed:

  • Node.js and npm
  • MongoDB (local or cloud-based MongoDB Atlas account)
  • Code editor of your choice (VSCode, Sublime Text, etc.)

Having a basic understanding of JavaScript, ES6 syntax, and RESTful API concepts will be beneficial.

Table of Contents

  1. Project Setup
  2. Backend Development
    • Setting Up MongoDB
    • Create Express Server
    • API Routes
  3. Frontend Development
    • Create React App
    • Components and UI
    • State Management
  4. Connecting Frontend and Backend
  5. Testing
  6. Deployment
  7. Conclusion

Project Setup

Initialize Node.js Project

Start by creating a new directory for your project. Open your terminal and run:

mkdir mern-todo-app
cd mern-todo-app
npm init -y

This will initialize a new Node.js project and create a package.json file.

Backend Development

Setting Up MongoDB

Local MongoDB Setup

To start your local MongoDB instance, run:

mongod --dbpath=/data/db

MongoDB Atlas Setup

For MongoDB Atlas, you'll need to create a cluster and obtain the connection URI. Keep this URI handy as we'll use it to connect our Express server to MongoDB.

Create an Express Server

Install Express and set up a basic server.

npm install express

Now create an index.js file in your project root and paste the following code:

const express = require('express');
const app = express();
const PORT = 3001;

app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});

API Routes

Install Mongoose

Mongoose will serve as the ORM for MongoDB. Install it using:

npm install mongoose

Model Schema

Create a file named todoModel.js:

const mongoose = require('mongoose');

const todoSchema = new mongoose.Schema({
task: String,
completed: Boolean
});

module.exports = mongoose.model('Todo', todoSchema);

CRUD Operations

In your index.js, let's implement CRUD operations:

const Todo = require('./todoModel');

app.get('/todos', async (req, res) => {
const todos = await Todo.find({});
res.json(todos);
});

app.post('/todos', async (req, res) => {
const newTodo = new Todo(req.body);
const savedTodo = await newTodo.save();
res.json(savedTodo);
});

app.put('/todos/:id', async (req, res) => {
const updatedTodo = await Todo.findByIdAndUpdate(req.params.id, req.body, { new: true });
res.json(updatedTodo);
});

app.delete('/todos/:id', async (req, res) => {
const deletedTodo = await Todo.findByIdAndDelete(req.params.id);
res.json(deletedTodo);
});

Frontend Development

Create React App

To initialize a React application, run:

npx create-react-app client

Components and UI

Let's build the UI components. Create a file named TodoList.js:

const TodoList = ({ todos }) => {
return (
<ul>
{todos.map(todo => (
<li key={todo._id}>{todo.task}</li>
))}
</ul>
);
};

State Management

In your App.js, manage the state of the To-Do list:

import React, { useState } from 'react';
import TodoList from './TodoList';

const App = () => {
const [todos, setTodos] = useState([]);

return (
<div>
<h1>To-Do List App</h1>
<TodoList todos={todos} />
</div>
);
};

Connecting Frontend and Backend

To connect both ends, we'll use axios to make HTTP requests:

npm install axios

Now, fetch and display the list of To-Do items in App.js:

import axios from 'axios';

// Fetch todos
axios.get('/todos').then(response => {
setTodos(response.data);
});

Testing

Make sure to write unit tests and end-to-end tests to validate each functionality. Use libraries like Jest and React Testing Library for frontend and Mocha/Chai for the backend.


Deployment

Given your experience in Linux Server Administration, deploying this app on a VPS would be an optimal choice. You can also consider cloud-based options like AWS or Heroku.


Conclusion

Building a To-Do List app with the MERN stack might seem daunting at first, but it becomes straightforward once you understand the flow and architecture. We've covered everything from setting up your development environment to deploying the application.

For more advanced topics and troubleshooting, refer to our knowledge base at Domain India Knowledgebase or submit a ticket at Domain India Support.

Happy Coding!


This guide aims to be a thorough resource for building a To-Do List application with the MERN stack. Each section can be a standalone tutorial, offering in-depth knowledge and practical examples. Feel free to bookmark this guide and refer back to it as you proceed with your development journey.


Was this answer helpful?

« Back