DEV Community

mibii
mibii

Posted on • Edited on

Dive into Web Development with the MERN Stack

Dive into Web Development with the MERN Stack: A Beginner's Guide
The web development world is booming, and you might be wondering how to jump in. Well, look no further than the MERN stack! This powerful combo of technologies is perfect for building modern, interactive web applications.

MERN stands for:

  • MongoDB: A flexible database that stores information in a format similar to JSON, making it easy to work with.
  • Express.js: A lightweight framework built on Node.js that simplifies building the server-side logic of your application.
  • React: A popular JavaScript library for creating user interfaces. It lets you break down your app into reusable components for clean and maintainable code.
  • Node.js: An environment that allows you to run JavaScript code outside of the browser, powering the server-side of your web app. Why Choose MERN?

There are many reasons why MERN is a favorite among developers:

Full-Stack Fun with JavaScript: Build your entire application using just JavaScript! This means less context switching and easier code maintenance.
Scales Like a Boss: MERN can handle massive amounts of data and traffic, making it ideal for growing web applications.
Fancy User Interfaces: React lets you create dynamic and engaging interfaces that keep users glued to your app.
A Helping Hand: MERN is an open-source technology with a large community, so you'll find plenty of resources and support online.
Getting Started: Building Your Foundation

Before diving into MERN, let's solidify some basics:

HTML & CSS: These are the building blocks of any web page. HTML defines the structure, while CSS adds the style.
JavaScript: This is the programming language that powers the interactivity of web applications. Learn about variables, functions, and how to control the flow of your code.
Node.js & npm: Node.js lets you run JavaScript outside the browser, and npm is the package manager that helps you install and manage code libraries.
Databases: Databases store your application's data. MERN uses MongoDB, but understanding basic database concepts is helpful.
Ready to Code? Let's Explore MERN!

Now that you have the foundation, let's break down each MERN technology:

MongoDB: This database stores data in flexible JSON-like documents, making it easy to add or remove information as needed.
Express.js: Think of Express.js as the organizer of your server-side code. It helps you define how your application responds to user requests.
React: React lets you build user interfaces with reusable components. These components can be simple or complex, allowing you to create intricate and dynamic interfaces.
Node.js: As mentioned before, Node.js is the runtime environment that lets you run JavaScript code outside the browser. This is where the magic happens on the server-side!
Building Your Skills: Practice Makes Perfect!

The best way to learn is by doing! Here are some project ideas to solidify your MERN skills:

CRUD App Challenge: Build a simple application that allows users to Create, Read, Update, and Delete data. This is a great way to practice working with databases and user interactions.
RESTful API with Express & MongoDB: APIs (Application Programming Interfaces) allow other applications to interact with your data. Build a RESTful API using Express.js and MongoDB to expose your data securely.
User Authentication & Authorization: Protect your app with user login and control what users can access. This involves implementing features like password storage and user roles.
Keep Learning and Keep Building!

Mastering MERN takes dedication and practice. Utilize online resources, tutorials, and developer communities to keep learning and growing your skills. The MERN stack offers a powerful and versatile toolkit for building modern web applications. Embrace the journey, and happy coding!

Building a Simple MERN Stack Application

Let's build a simple MERN stack application to get you started. We'll create a basic "To-Do List" application where users can add, view, update, and delete tasks.

Prerequisites

Basic knowledge of HTML, CSS, and JavaScript.

Node.js and npm installed on your machine.

MongoDB installed or access to a MongoDB cloud instance (e.g., MongoDB Atlas).

Project Structure

mern-todo-app/
|-- backend/
| |-- models/
| | |-- Todo.js
| |-- routes/
| | |-- todos.js
| |-- app.js
| |-- package.json
|
|-- frontend/
| |-- public/
| |-- src/
| | |-- components/
| | | |-- TodoItem.js
| | | |-- TodoList.js
| | | |-- AddTodo.js
| | |-- App.js
| | |-- index.js
| |-- package.json
|
|-- README.md
Backend Setup
Initialize the backend project:

mkdir backend
 cd backend
 npm init -y
 npm install express mongoose cors
Enter fullscreen mode Exit fullscreen mode

Create the Express server:

backend/app.js:

    const express = require('express');
    const mongoose = require('mongoose');
    const cors = require('cors');
    const app = express();
    const todoRoutes = require('./routes/todos');

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

    app.use(cors());
    app.use(express.json());
    app.use('/api/todos', todoRoutes);

    app.listen(5000, () => {
        console.log('Server is running on port 5000');
    });
Enter fullscreen mode Exit fullscreen mode

Define the Todo model:

backend/models/Todo.js:

   const mongoose = require('mongoose');

    const todoSchema = new mongoose.Schema({
        text: { type: String, required: true },
        completed: { type: Boolean, default: false }
    });

    module.exports = mongoose.model('Todo', todoSchema);
Enter fullscreen mode Exit fullscreen mode

Create the routes:

backend/routes/todos.js:

    const express = require('express');
    const Todo = require('../models/Todo');
    const router = express.Router();

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

    // Create a new todo
    router.post('/', async (req, res) => {
        const newTodo = new Todo({
            text: req.body.text
        });
        await newTodo.save();
        res.json(newTodo);
    });

    // Update a todo
    router.put('/:id', async (req, res) => {
        const todo = await Todo.findByIdAndUpdate(req.params.id, req.body, { new: true });
        res.json(todo);
    });

    // Delete a todo
    router.delete('/:id', async (req, res) => {
        await Todo.findByIdAndDelete(req.params.id);
        res.json({ message: 'Todo deleted' });
    });

    module.exports = router;
Enter fullscreen mode Exit fullscreen mode

Frontend Setup

Initialize the frontend project:

 npx create-react-app frontend
 cd frontend
 npm install axios
Enter fullscreen mode Exit fullscreen mode

Create the components:

frontend/src/components/AddTodo.js:

    import React, { useState } from 'react';
    import axios from 'axios';

    const AddTodo = ({ onAdd }) => {
        const [text, setText] = useState('');

        const handleSubmit = async (e) => {
            e.preventDefault();
            if (text.trim()) {
                const res = await axios.post('http://localhost:5000/api/todos', { text });
                onAdd(res.data);
                setText('');
            }
        };

        return (
            <form onSubmit={handleSubmit}>
                <input
                    type="text"
                    value={text}
                    onChange={(e) => setText(e.target.value)}
                    placeholder="Add a new task"
                />
                <button type="submit">Add</button>
            </form>
        );
    };

    export default AddTodo;
Enter fullscreen mode Exit fullscreen mode

frontend/src/components/TodoItem.js:

    import React from 'react';
    import axios from 'axios';

    const TodoItem = ({ todo, onUpdate, onDelete }) => {
        const handleToggle = async () => {
            const res = await axios.put(`http://localhost:5000/api/todos/${todo._id}`, {
                completed: !todo.completed
            });
            onUpdate(res.data);
        };

        const handleDelete = async () => {
            await axios.delete(`http://localhost:5000/api/todos/${todo._id}`);
            onDelete(todo._id);
        };

        return (
            <div>
                <span
                    style={{ textDecoration: todo.completed ? 'line-through' : 'none' }}
                    onClick={handleToggle}
                >
                    {todo.text}
                </span>
                <button onClick={handleDelete}>Delete</button>
            </div>
        );
    };

    export default TodoItem;
Enter fullscreen mode Exit fullscreen mode

frontend/src/components/TodoList.js:

    import React from 'react';
    import TodoItem from './TodoItem';

    const TodoList = ({ todos, onUpdate, onDelete }) => {
        return (
            <div>
                {todos.map((todo) => (
                    <TodoItem key={todo._id} todo={todo} onUpdate={onUpdate} onDelete={onDelete} />
                ))}
            </div>
        );
    };

    export default TodoList;
Enter fullscreen mode Exit fullscreen mode

Create the main App component:

frontend/src/App.js:

    import React, { useState, useEffect } from 'react';
    import axios from 'axios';
    import AddTodo from './components/AddTodo';
    import TodoList from './components/TodoList';

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

        useEffect(() => {
            const fetchTodos = async () => {
                const res = await axios.get('http://localhost:5000/api/todos');
                setTodos(res.data);
            };
            fetchTodos();
        }, []);

        const handleAdd = (newTodo) => {
            setTodos([...todos, newTodo]);
        };

        const handleUpdate = (updatedTodo) => {
            setTodos(todos.map(todo => (todo._id === updatedTodo._id ? updatedTodo : todo)));
        };

        const handleDelete = (id) => {
            setTodos(todos.filter(todo => todo._id !== id));
        };

        return (
            <div>
                <h1>To-Do List</h1>
                <AddTodo onAdd={handleAdd} />
                <TodoList todos={todos} onUpdate={handleUpdate} onDelete={handleDelete} />
            </div>
        );
    };

    export default App;
Enter fullscreen mode Exit fullscreen mode

Start the application:

Open two terminals: one for the backend and one for the frontend.

Backend:

 cd backend
  node app.js
Enter fullscreen mode Exit fullscreen mode

Frontend:

 cd frontend
  npm start
Enter fullscreen mode Exit fullscreen mode

Your application should now be running on http://localhost:3000 (frontend) and http://localhost:5000 (backend).

Conclusion
Congratulations! You've built a simple MERN stack application. This "To-Do List" app is just the beginning. You can expand it with more features, improve the UI, or even deploy it to the cloud. Keep exploring and building to master the MERN stack!

Here is my React MERN stack sample web app.

The idea of a web application is a service to find other people services. Anyone can add as a mark on the map. (which will contain his telegram contact, approximate location, you can also indicate a short text about you, website and picture). To get to the map you need to use a telegram bot. (There is a link on the site) Establish horizontal connections and contacts - without intermediaries. Anyone who sees your tag sees your telegram contact and will be able to contact you directly via telegram. https://infometka.com/

Image description

Top comments (0)