,

Creating Todos App using React.js and Express.js

Posted by

Todos App with React.js + Express.js

Welcome to Todos App

In this article, we will be discussing how to create a simple Todos app using React.js for the front-end and Express.js for the back-end.

Setting up the Project

First, you need to have Node.js and npm installed on your machine. Then, create a new directory for your project and run the following commands in your terminal:


$ npx create-react-app todos-app
$ cd todos-app
$ npm install express

Creating the Front-End

Now, let’s create the front-end of our app using React.js. Inside the ‘todos-app’ directory, create a new file called ‘Todos.js’ and add the following code:

import React, { useState } from 'react';

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

    const addTodo = (todo) => {
        setTodos([...todos, todo]);
    };

    return (
        

Todos

    {todos.map((todo, index) => (
  • {todo}
  • ))}
); }; export default Todos;

Creating the Back-End

Next, let’s create the back-end of our app using Express.js. Inside the ‘todos-app’ directory, create a new file called ‘server.js’ and add the following code:

const express = require('express');
const app = express();
const port = 5000;

app.use(express.json());

app.post('/addTodo', (req, res) => {
    const todo = req.body.todo;
    // Add the todo to the database
    res.status(200).json({ message: 'Todo added successfully' });
});

app.listen(port, () => {
    console.log(`Server is running at http://localhost:${port}`);
});
    

Connecting the Front-End and Back-End

Now that we have our front-end and back-end set up, we need to connect them together. Inside the ‘Todos.js’ file, add the following code to make a POST request to the back-end when the ‘Add’ button is clicked:

const addTodo = (todo) => {
    fetch('http://localhost:5000/addTodo', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({ todo }),
    })
    .then((res) => res.json())
    .then((data) => console.log(data.message))
    .catch((error) => console.log(error));
};
    

Running the App

Finally, run the following commands in your terminal to start the front-end and back-end servers:


$ npm start // to start the front-end server
$ node server.js // to start the back-end server

Now, open your web browser and go to ‘http://localhost:3000’ to see your Todos app in action!

0 0 votes
Article Rating
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@plica06
10 months ago

Really good tutorial , I'm gonna try this out !!