How to

Building THE MOST practical Todolist with React and Websockets 🪄✨

In this article, you'll learn how to build a team to-do list with React.js and Socket.io. Users can create, read, and delete to-dos and add comments to each to-do via Socket.io. You'll also learn how to add notifications to the application when you create or delete a to-do item.

Nevo David
Nevo DavidOctober 11, 2022

Novu – the first open-source notification infrastructure

Just a quick background about us. Novu is the first open-source notification infrastructure. We basically help to manage all the product notifications. It can be In-App (the bell icon like you have in the Dev Community – Websockets), Emails, SMSs and so on.

I would be super happy if you could give us a star! It will help me to make more articles every week 🚀
https://github.com/novuhq/novu

Novu
We will also send some awesome swag during Hacktoberfest 😇

What is Socket.io?

Socket.io is a popular JavaScript library that allows us to create real-time, bi-directional communication between web browsers and a Node.js server. It is a highly performant and reliable library designed to process a large volume of data with minimal delay. It follows the WebSocket protocol and provides better functionalities, such as fallback to HTTP long-polling or automatic reconnection, which enables us to build efficient real-time applications.

Todolist

How to create a real-time connection with React & Socket.io

Here, we’ll set up the project environment for the to-do list application. You’ll also learn how to add Socket.io to a React and Node.js application and connect both development servers for real-time communication via Socket.io.

Create the project folder containing two sub-folders named client and server.

1mkdir todo-list
2cd todo-list
3mkdir client server
4

Navigate into the client folder via your terminal and create a new React.js project.

1cd client
2npx create-react-app ./
3

Install Socket.io client API and React Router. React Router is a JavaScript library that enables us to navigate between pages in a React application.

1npm install socket.io-client react-router-dom
2

Delete the redundant files such as the logo and the test files from the React app, and update the App.js file to display Hello World as below.

1function App() {
2    return (
3        <div>
4            <p>Hello World!</p>
5        </div>
6    );
7}
8export default App;

Navigate into the server folder and create a package.json file.

1cd server & npm init -y

Install Express.js, CORS, Nodemon, and Socket.io Server API.

Express.js is a fast, minimalist framework that provides several features for building web applications in Node.js. CORS is a Node.js package that allows communication between different domains.

Nodemon is a Node.js tool that automatically restarts the server after detecting file changes, and Socket.io allows us to configure a real-time connection on the server.

1npm install express cors nodemon socket.io

Create an index.js file – the entry point to the web server.

1touch index.js

Set up a simple Node.js server using Express.js. The code snippet below returns a JSON object when you visit the http://localhost:4000/api in your browser.

1//👇🏻index.js
2const express = require("express");
3const app = express();
4const PORT = 4000;
5
6app.use(express.urlencoded({ extended: true }));
7app.use(express.json());
8
9app.get("/api", (req, res) => {
10    res.json({
11        message: "Hello world",
12    });
13});
14
15app.listen(PORT, () => {
16    console.log(`Server listening on ${PORT}`);
17});

Import the HTTP and the CORS library to allow data transfer between the client and the server domains.

1const express = require("express");
2const app = express();
3const PORT = 4000;
4
5app.use(express.urlencoded({ extended: true }));
6app.use(express.json());
7
8//👇🏻 New imports
9const http = require("http").Server(app);
10const cors = require("cors");
11
12app.use(cors());
13
14app.get("/api", (req, res) => {
15    res.json({
16        message: "Hello world",
17    });
18});
19
20http.listen(PORT, () => {
21    console.log(`Server listening on ${PORT}`);
22});

Next, add Socket.io to the project to create a real-time connection. Before the app.get()
block, copy the code below.

1//👇🏻 New imports
2.....
3const socketIO = require('socket.io')(http, {
4    cors: {
5        origin: "http://localhost:3000"
6    }
7});
8
9//👇🏻 Add this before the app.get() block
10socketIO.on('connection', (socket) => {
11    console.log(`⚡: ${socket.id} user just connected!`);
12
13    socket.on('disconnect', () => {
14      socket.disconnect()
15      console.log('🔥: A user disconnected');
16    });
17});

From the code snippet above, the socket.io("connection") function establishes a connection with the React app, then creates a unique ID for each socket and logs the ID to the console whenever a user visits the web page.

When you refresh or close the web page, the socket fires the disconnect event showing that a user has disconnected from the socket.

Configure Nodemon by adding the start command to the list of scripts in the package.json file. The code snippet below starts the server using Nodemon.

1//👇🏻 In server/package.json
2
3"scripts": {
4    "test": "echo \"Error: no test specified\" && exit 1",
5    "start": "nodemon index.js"
6  },

You can now run the server with Nodemon by using the command below.

1npm start

Building the user interface

Here, we’ll create the user interface for the to-do list application. Users will be able to sign in, add and delete a to-do, and add comments to every to-do.

Navigate into the client/src folder and create a components folder containing a Home.js and Main.js file.

1cd client
2mkdir components
3cd components
4touch Home.js Main.js

Update the App.js file to render the newly created components on different routes via React Router.

1import React from "react";
2import socketIO from "socket.io-client";
3import { BrowserRouter, Routes, Route } from "react-router-dom";
4import Main from "./components/Main";
5import Home from "./components/Home";
6
7const socket = socketIO.connect("http://localhost:4000");
8
9const App = () => {
10    return (
11        <BrowserRouter>
12            <Routes>
13                <Route path='/' element={<Home />} />
14                <Route path='/app' element={<Main socket={socket} />} />
15            </Routes>
16        </BrowserRouter>
17    );
18};
19
20export default App;

Navigate into the src/index.css file and copy the code below. It contains all the CSS required for styling this project.

1@import url("https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@300;400;500;600;700&display=swap");
2* {
3    box-sizing: border-box;
4    margin: 0;
5    padding: 0;
6    font-family: "Space Grotesk", sans-serif;
7}
8.navbar {
9    width: 100%;
10    height: 10vh;
11    background-color: #256d85;
12    display: flex;
13    align-items: center;
14    justify-content: space-between;
15    padding: 0 20px;
16    color: #dff6ff;
17}
18.form {
19    width: 100%;
20    min-height: 20vh;
21    display: flex;
22    align-items: center;
23    justify-content: center;
24    padding: 0 30px;
25}
26.input {
27    padding: 10px 15px;
28    width: 80%;
29    margin-right: 15px;
30}
31.form__cta,
32.home__form > button {
33    width: 200px;
34    cursor: pointer;
35    padding: 10px;
36    height: 45px;
37    font-size: 16px;
38    background-color: #256d85;
39    color: #dff6ff;
40    border: none;
41    outline: none;
42    border-radius: 3px;
43}
44.todo__container {
45    width: 100%;
46    display: flex;
47    align-items: center;
48    flex-direction: column;
49    min-height: 300px;
50}
51.todo__item {
52    display: flex;
53    align-items: center;
54    width: 70%;
55    padding: 20px;
56    background-color: #ddd;
57    margin: 10px 0;
58    justify-content: space-between;
59    color: #06283d;
60}
61
62.deleteBtn {
63    padding: 5px 10px;
64    background-color: rgb(202, 22, 22);
65    border: none;
66    outline: none;
67    color: #fff;
68    cursor: pointer;
69}
70.deleteBtn:hover {
71    color: rgb(202, 22, 22);
72    background-color: #fff;
73}
74.commentsBtn {
75    padding: 5px 10px;
76    margin-right: 10px;
77    outline: none;
78    cursor: pointer;
79    border: none;
80    background-color: #fff;
81}
82.commentsBtn:hover {
83    background-color: #ddd;
84    border: 1px solid #000;
85}
86.modal {
87    min-height: 100vh;
88    width: 100%;
89    position: fixed;
90    top: 0;
91    background-color: #fff;
92    display: flex;
93    align-items: center;
94    justify-content: center;
95}
96.modal__container {
97    width: 70%;
98    background-color: #fff;
99    min-height: 80vh;
100    padding: 30px;
101    border-radius: 3px;
102    border: 1px solid #333;
103}
104.modal__container > h3 {
105    margin-bottom: 30px;
106}
107.comment__form {
108    display: flex;
109    margin-bottom: 30px;
110    align-items: center;
111}
112.comment__form > input {
113    padding: 10px;
114    border: 1px solid #256d85;
115    width: 70%;
116    margin-right: 20px;
117}
118.comment {
119    margin-bottom: 5px;
120}
121.comment__form > button {
122    padding: 15px 20px;
123    cursor: pointer;
124    background-color: #256d85;
125    color: #fff;
126    outline: none;
127    border: none;
128    height: 45px;
129}
130.home {
131    width: 100%;
132    min-height: 100vh;
133    display: flex;
134    flex-direction: column;
135    align-items: center;
136    justify-content: center;
137}
138.home__form {
139    width: 100%;
140    display: flex;
141    flex-direction: column;
142    align-items: center;
143}
144.home__form > * {
145    margin-bottom: 10px;
146}
147.home > h2 {
148    margin-bottom: 15px;
149}

The Home page

Here, the application accepts the username and saves it in the local storage for user identification. Copy the code below into the Home component.

1import React, { useState } from "react";
2import { useNavigate } from "react-router-dom";
3
4const Home = () => {
5    const [username, setUsername] = useState("");
6    const navigate = useNavigate();
7
8    const handleSubmit = (e) => {
9        e.preventDefault();
10        localStorage.setItem("_username", username);
11        //👇🏻 Navigates to the application
12        navigate("/app");
13    };
14    return (
15        <div className='home'>
16            <h2>Sign in to your todo-list</h2>
17            <form onSubmit={handleSubmit} className='home__form'>
18                <label htmlFor='username'>Your Username</label>
19                <input
20                    value={username}
21                    required
22                    onChange={(e) => setUsername(e.target.value)}
23                    className='input'
24                />
25                <button>SIGN IN</button>
26            </form>
27        </div>
28    );
29};
30
31export default Home;

The Main component

Here, we’ll build the user interface for the central part of the application.

Interface

Copy the code snippet below into the Main.js file.

1import React, { useState } from "react";
2import Nav from "./Nav";
3
4function Main({ socket }) {
5    const [todo, setTodo] = useState("");
6
7    //👇🏻 Generates a random string as the todo ID
8    const generateID = () => Math.random().toString(36).substring(2, 10);
9
10    const handleAddTodo = (e) => {
11        e.preventDefault();
12    //👇🏻 Every todo has this structure - id, todo & comments.
13        console.log({
14            id: generateID(),
15            todo,
16            comments: [],
17        });
18        setTodo("");
19    };
20
21    return (
22        <div>
23            <Nav />
24            <form className='form' onSubmit={handleAddTodo}>
25                <input
26                    value={todo}
27                    onChange={(e) => setTodo(e.target.value)}
28                    className='input'
29                    required
30                />
31                <button className='form__cta'>ADD TODO</button>
32            </form>
33
34            <div className='todo__container'>
35                <div className='todo__item'>
36                    <p>Contributing to open-source</p>
37                    <div>
38                        <button className='commentsBtn'>View Comments</button>
39                        <button className='deleteBtn'>DELETE</button>
40                    </div>
41                </div>
42
43                <div className='todo__item'>
44                    <p>Coffee chat with the team</p>
45                    <div>
46                        <button className='commentsBtn'>View Comments</button>
47                        <button className='deleteBtn'>DELETE</button>
48                    </div>
49                </div>
50
51                <div className='todo__item'>
52                    <p>Work on my side projects</p>
53                    <div>
54                        <button className='commentsBtn'>View Comments</button>
55                        <button className='deleteBtn'>DELETE</button>
56                    </div>
57                </div>
58            </div>
59        </div>
60    );
61}
62
63export default Main;

The code snippet above represents the user interface that enables users to create a to-do, view comments, and delete existing to-dos.

The Nav component is the navigation bar for the application – later in this tutorial, we’ll send notifications with Novu within this component.

Create the Nav component and copy the code below into it:

1//👇🏻 Within /src/components/Nav.js
2import React from "react";
3
4const Nav = () => {
5    return (
6        <nav className='navbar'>
7            <h2>Todo List</h2>
8        </nav>
9    );
10};
11
12export default Nav;

Congratulations!🔥 We’ve created the user interface for the application. In the upcoming sections, you’ll learn how to send real-time data with Socket.io and notifications with Novu.

How to create a new to-do

In this section, I’ll guide you through creating new to-dos and display them on the React app with Socket.io.

Update the handleAddTodo function within the Main.js file to send the new to-do to the server via Socket.io.

1const handleAddTodo = (e) => {
2    e.preventDefault();
3    //👇🏻 Sends a event - addTodo via Socket.io
4 // containing the id, todo, and the comments array
5    socket.emit("addTodo", {
6        id: generateID(),
7        todo,
8        comments: [],
9    });
10    setTodo("");
11};

Create a listener to the event on the server.

1socketIO.on("connection", (socket) => {
2    console.log(`⚡: ${socket.id} user just connected!`);
3
4    socket.on("addTodo", (todo) => {
5        //👇🏻 todo - contains the object from the React app
6        console.log(todo);
7    });
8
9    socket.on("disconnect", () => {
10        socket.disconnect();
11        console.log("🔥: A user disconnected");
12    });
13});

Create an array on the backend server that holds all the to-dos, and add the new to-do to the list.

1//👇🏻 Array containing all the to-dos
2let todoList = [];
3
4socketIO.on("connection", (socket) => {
5    console.log(`⚡: ${socket.id} user just connected!`);
6
7    socket.on("addTodo", (todo) => {
8        //👇🏻 Adds the to-do object to the list of to-dos
9        todoList.unshift(todo);
10        //👇🏻 Sends all the to-dos to the React app
11        socket.emit("todos", todoList);
12    });
13
14    socket.on("disconnect", () => {
15        socket.disconnect();
16        console.log("🔥: A user disconnected");
17    });
18});

Create a listener for the to-dos on the React app via the useEffect hook. Copy the code below:

1//In src/components/Main.js
2useEffect(() => {
3    socket.on("todos", (data) => console.log(data));
4}, [socket]);

Display the to-dos as below:

1import React, { useState, useEffect } from "react";
2import Nav from "./Nav";
3
4function Main({ socket }) {
5    const [todo, setTodo] = useState("");
6    const [todoList, setTodoList] = useState([]);
7
8    const generateID = () => Math.random().toString(36).substring(2, 10);
9
10    const handleAddTodo = (e) => {
11        e.preventDefault();
12        socket.emit("addTodo", {
13            id: generateID(),
14            todo,
15            comments: [],
16        });
17        setTodo("");
18    };
19
20    useEffect(() => {
21        socket.on("todos", (data) => setTodoList(data));
22    }, [socket]);
23
24    return (
25        <div>
26            <Nav />
27            <form className='form' onSubmit={handleAddTodo}>
28                <input
29                    value={todo}
30                    onChange={(e) => setTodo(e.target.value)}
31                    className='input'
32                    required
33                />
34                <button className='form__cta'>ADD TODO</button>
35            </form>
36
37            <div className='todo__container'>
38                {todoList.map((item) => (
39                    <div className='todo__item' key={item.id}>
40                        <p>{item.todo}</p>
41                        <div>
42                            <button className='commentsBtn'>View Comments</button>
43
44                            <button className='deleteBtn'>DELETE</button>
45                        </div>
46                    </div>
47                ))}
48            </div>
49        </div>
50    );
51}
52
53export default Main;

So far, we can only view the existing to-dos when we add one. Next, let’s make it possible for us to display the to-dos when we load the page.

Create a route on the server that returns the to-do list.

1app.get("/api", (req, res) => {
2    res.json(todoList);
3});

Update the useEffect hook to fetch the to-do list from the server, and listen when for new to-dos.

1useEffect(() => {
2    function fetchTodos() {
3        fetch("http://localhost:4000/api")
4            .then((res) => res.json())
5            .then((data) => setTodoList(data))
6            .catch((err) => console.error(err));
7    }
8    fetchTodos();
9
10    socket.on("todos", (data) => setTodoList(data));
11}, [socket]);

Congratulations, we can now add new to-dos to the to-do list.

Image description

How to delete existing to-dos

Add an onClick event to the delete button that gets the ID of the selected to-do.

1<button className='deleteBtn' onClick={() => deleteTodo(item.id)}>
2    DELETE
3</button>

Create the deleteTodo function and send the to-do’s ID to the server via Socket.io.

1const deleteTodo = (id) => socket.emit("deleteTodo", id);

Create a listener for the deleteTodo event that removes the to-do via its ID from the to-do list.

1//👇🏻 Array containing all the to-dos
2let todoList = [];
3
4socketIO.on("connection", (socket) => {
5    console.log(`⚡: ${socket.id} user just connected!`);
6
7    socket.on("addTodo", (todo) => {
8        todoList.unshift(todo);
9        socket.emit("todos", todoList);
10    });
11
12    //👇🏻 Filters the array of to-dos and
13    //   sends the updated to-do to the React app.
14    socket.on("deleteTodo", (id) => {
15        todoList = todoList.filter((todo) => todo.id !== id);
16        //👇🏻 Sends the updated to-do to the React app
17        socket.emit("todos", todoList);
18    });
19
20    socket.on("disconnect", () => {
21        socket.disconnect();
22        console.log("🔥: A user disconnected");
23    });
24});

You can now add and delete each to-do via Socket.io. Next, you’ll learn how to add and display comments for each to-do.

youcan

How to display and add comments for each to-do

In this section, I’ll guide you through adding comments to each to-do, and you’ll also learn how to create Modals in React.

Creating a modal in React.js

Create a Modal.js file that will contain the comments for each to-do as below:

1import React, { useState } from "react";
2
3const Modal = ({ socket }) => {
4    const [comment, setComment] = useState("");
5
6    const addComment = (e) => {
7        e.preventDefault();
8        console.log({ comment });
9        setComment("");
10    };
11
12    return (
13        <div className='modal'>
14            <div className='modal__container'>
15                <h3>Comments</h3>
16                <form className='comment__form' onSubmit={addComment}>
17                    <input
18                        className='comment__input'
19                        type='text'
20                        value={comment}
21                        onChange={(e) => setComment(e.target.value)}
22                        required
23                    />
24                    <button>Add Comment</button>
25                </form>
26                <div className='comments__container'>
27                    <div className='comment'>
28                        <p>
29                            <strong>Nevo - </strong> Hello guys
30                        </p>
31                    </div>
32                </div>
33            </div>
34        </div>
35    );
36};
37
38export default Modal;

To make this component display as a Modal, we need to give it some styling as done below within the src/index.css file, especially the position and z-index property.

1.modal {
2    min-height: 100vh;
3    width: 100%;
4    position: fixed;
5    z-index: 10;
6    top: 0;
7    background-color: #fff;
8    display: flex;
9    align-items: center;
10    justify-content: center;
11}

Next, let’s toggle the Modal.js component when we click on the View Comment button within the Main.js file.

1import React, { useState, useEffect } from "react";
2import Nav from "./Nav";
3import Modal from "./Modal";
4
5function Main({ socket }) {
6    const [todo, setTodo] = useState("");
7    const [todoList, setTodoList] = useState([]);
8    const [showModal, setShowModal] = useState(false);
9
10    const toggleModal = () => setShowModal(!showModal);
11    //...other functions
12    return (
13        <div>
14            ...
15            <div className='todo__container'>
16                {todoList.map((item) => (
17                    <div className='todo__item' key={item.id}>
18                        <p>{item.todo}</p>
19                        <div>
20                            {/*👇🏻 This button toggles the Modal component---*/}
21                            <button className='commentsBtn' onClick={toggleModal}>
22                                View Comments
23                            </button>
24                            <button className='deleteBtn' onClick={() => deleteTodo(item.id)}>
25                                DELETE
26                            </button>
27                        </div>
28                    </div>
29                ))}
30            </div>
31            {/*👇🏻 The Modal replaces the Main component*/}
32            {showModal ? (
33                <Modal showModal={showModal} setShowModal={setShowModal} />
34            ) : (
35                ""
36            )}
37        </div>
38    );
39}
40
41export default Main;

Res

Since we’ve been able to display the Modal when we click on the View Button, next, let’s toggle the Modal when we click outside the comments container.

Update the Modal.js file as below:

1import React, { useState, useRef } from "react";
2
3const Modal = ({ socket, showModal, setShowModal }) => {
4    const [comment, setComment] = useState("");
5
6    const modalRef = useRef();
7    //👇🏻 If the container (modalRef) is clicked, it closes the modal.
8    const closeModal = (e) => {
9        if (modalRef.current === e.target) {
10            setShowModal(!showModal);
11        }
12    };
13
14    const addComment = (e) => {
15        e.preventDefault();
16        console.log({ comment });
17        setComment("");
18    };
19    return (
20        <div className='modal' onClick={closeModal} ref={modalRef}>
21            ...
22        </div>
23    );
24};

Image description

Congratulations!💃🏻 You’ve learnt how to add Modals to a React application. Hence, let’s make it possible to users to add and display comments.

Displaying the to-do comments

Update the toggleModal function within the Main.js file to send the ID of the selected to-do to the server.

1const toggleModal = (todoId) => {
2    socket.emit("viewComments", todoId);
3    setShowModal(!showModal);
4};

Create a listener on the server that accepts the to-do ID, fetches its details, and sends it back to the React app.

1socket.on("viewComments", (id) => {
2    for (let i = 0; i < todoList.length; i++) {
3        if (id === todoList[i].id) {
4            //👇🏻 sends the todo details back to the React app for display
5            socket.emit("commentsReceived", todoList[i]);
6        }
7    }
8});

Create a listener for the commentsReceived event within the Modal.js file.

1useEffect(() => {
2    socket.on("commentsReceived", (todo) => console.log(todo));
3}, [socket]);

Render the comments by copying the below:

1import React, { useEffect, useRef, useState } from "react";
2
3const Modal = ({ showModal, setShowModal, socket }) => {
4    const modalRef = useRef();
5    const [comment, setComment] = useState("");
6    const [comments, setComments] = useState([]);
7
8    const closeModal = (e) => {
9        if (modalRef.current === e.target) {
10            setShowModal(!showModal);
11        }
12    };
13
14    const addComment = (e) => {
15        e.preventDefault();
16        console.log({ comment });
17        setComment("");
18    };
19
20    //👇🏻 Listens for the todo details from the server
21    useEffect(() => {
22        socket.on("commentsReceived", (todo) => setComments(todo.comments));
23    }, [socket]);
24
25    return (
26        <div className='modal' onClick={closeModal} ref={modalRef}>
27            <div className='modal__container'>
28                <h3>Comments</h3>
29                <form className='comment__form' onSubmit={addComment}>
30                    <input
31                        className='comment__input'
32                        type='text'
33                        value={comment}
34                        onChange={(e) => setComment(e.target.value)}
35                        required
36                    />
37                    <button>Add Comment</button>
38                </form>
39
40                {/*👇🏻 Displays the comments --- */}
41                <div className='comments__container'>
42                    {comments.length > 0 ? (
43                        comments.map((item, index) => (
44                            <div className='comment' key={index}>
45                                <p>
46                                    <strong>{item.name} - </strong> {item.text}
47                                </p>
48                            </div>
49                        ))
50                    ) : (
51                        <p>No comments available yet...</p>
52                    )}
53                </div>
54            </div>
55        </div>
56    );
57};
58
59export default Modal;

Adding Comments to to-dos

Create a state within the Main.js that holds the ID of the selected to-do. Pass the state to the Modal.js component.

1const toggleModal = (itemId) => {
2    socket.emit("viewComments", itemId);
3    //👇🏻 Pass this ID into the Modal component
4    setSelectedItemID(itemId);
5    setShowModal(!showModal);
6};

Update the addComment function within the Modal.js file to send the comment details to the server.

1const addComment = (e) => {
2    e.preventDefault();
3    socket.emit("updateComment", {
4        todoID: selectedItemID, //The ID passed from the Main.js file
5        comment,
6        user: localStorage.getItem("_username"),
7    });
8    setComment("");
9};

Create a listener for the addComment event on the server that adds the comment to the to-do’s comments.

1socket.on("updateComment", (data) => {
2    //👇🏻 Destructure the items from the object
3    const { user, todoID, comment } = data;
4
5    for (let i = 0; i < todoList.length; i++) {
6        //👇🏻 Gets the todo
7        if (todoID === todoList[i].id) {
8            //👇🏻 Add the comment to the list of comments
9            todoList[i].comments.push({ name: user, text: comment });
10            //👇🏻 Sends an update to React app
11            socket.emit("commentsReceived", todoList[i]);
12        }
13    }
14});

Congratulations! We can now add comments to each to-do and display them on the React app.

comments

EXTRA: Sending notifications with Novu

If you want to add notifications to the application when a user adds a comment or a new to-do, you can do that easily with Novu within the Nav.js component.

Novu allows you to add various notification types, such as email, SMS, and in-app notifications.

How to add Novu to a React and Node.js application

To add the in-app notification, install the Novu Node.js SDK on the server and the Notification Center in the React app.

1👇🏻 Install on the client
2npm install @novu/notification-center
3
4👇🏻 Install on the server
5npm install @novu/node

Create a Novu project by running the code below. A personalized dashboard is available to you.

1👇🏻 Install on the client
2npx novu init

You will need to sign in with GitHub before creating a Novu project. The code snippet below contains the steps you should follow after running npx novu init

1Now let's setup your account and send your first notification
2❓ What is your application name? Devto Clone
3❓ Now lets setup your environment. How would you like to proceed?
4   > Create a free cloud account (Recommended)
5❓ Create your account with:
6   > Sign-in with GitHub
7❓ I accept the Terms and Condidtions (https://novu.co/terms) and have read the Privacy Policy (https://novu.co/privacy)
8    > Yes
9✔️ Create your account successfully.
10
11We've created a demo web page for you to see novu notifications in action.
12Visit: http://localhost:57807/demo to continue

Visit the demo web page http://localhost:57807/demo, copy your subscriber ID from the page, and click the Skip Tutorial button. We’ll be using it later in this tutorial.

Demo

Update the components/Nav.jsfile to contain Novu and its required elements for in-app notifications from the documentation.

1import React from "react";
2import {
3    NovuProvider,
4    PopoverNotificationCenter,
5    NotificationBell,
6} from "@novu/notification-center";
7import { useNavigate } from "react-router-dom";
8
9const Nav = () => {
10    const navigate = useNavigate();
11
12    const onNotificationClick = (notification) =>
13        navigate(notification.cta.data.url);
14    return (
15        <nav className='navbar'>
16            <h2>Todo List</h2>
17            <div>
18                <NovuProvider
19                    subscriberId='<YOUR_SUBSCRIBER_ID'
20                    applicationIdentifier='<YOUR_APP_ID>'
21                >
22                    <PopoverNotificationCenter
23                        onNotificationClick={onNotificationClick}
24                        colorScheme='light'
25                    >
26                        {({ unseenCount }) => (
27                            <NotificationBell unseenCount={unseenCount} />
28                        )}
29                    </PopoverNotificationCenter>
30                </NovuProvider>
31            </div>
32        </nav>
33    );
34};
35
36export default Nav;

The code snippet above adds Novu notification bell icon to the Nav component, enabling us to view all the notifications from the application.

💡 The NovuProvider component requires your Subscriber ID – copied earlier from http://localhost:57807/demoand your application ID available in the Settings section under API Keys on the Novu Manage Platform.

settings

Next, let’s create the workflow for the application, which describes the features you want to add to the application.

Select Notification from the Development sidebar and create a notification template. Select the newly created template, click on Workflow Editor, and ensure the workflow is as below:

digest

From the image above, Novu triggers the Digest engine before sending the in-app notification.

Novu Digest allows us to control how we want to send notifications within the application. It collects multiple trigger events and sends them as a single message. The image above sends notifications every 2 minutes, and it can be effective when you have many users and frequent updates.

Click the In-Appstep and edit the notification template to contain the content below.

1{{userId}} added a new to-do.

💡 💡 Novu allows you to add dynamic content or data to the templates using the Handlebars templating engine. The data for the username variable will be inserted into the template as a payload from the request.

Save the template by clicking Update button and head back to your code editor.

Adding Novu to the application

Import Novu from the package and create an instance using your API Key on the server.

1//server/index.js
2
3const { Novu } = require("@novu/node");
4const novu = new Novu("<YOUR_API_KEY>");

Create a function that sends the notification via Novu to the React app.

1const sendNotification = async (template_id) => {
2    try {
3        const result = await novu.trigger(template_id, {
4            to: {
5                subscriberId: <SUBSCRIBER_ID>,
6            },
7        });
8        console.log(result);
9    } catch (err) {
10        console.error("Error >>>>", { err });
11    }
12};
13
14socket.on("addTodo", (todo) => {
15        todoList.unshift(todo);
16        socket.emit("todos", todoList);
17
18    //👇🏻 Triggers the notification via Novu
19        sendNotification("<TEMPLATE_ID>");
20    });

The code snippet above sends a notification to all users when a new to-do is added to the application.

Notifications

Congratulation you have finished building the Todolist! 🎉

Conclusion

So far, you’ve learnt how to set up Socket.io in a React and Node.js application, and communicate between a server and a client via Socket.io.

This is a demo of what you can build using Socket.io and React. Feel free to improve the application by adding authentication, a real-time database, and notifications via Novu when a user drops a comment.
The source code for this tutorial is available here:
https://github.com/novuhq/blog/tree/main/todolist-with-react-and-socketIO

Finished

P.S Novu is sending awesome swag on Hacktoberfest! Come and participate! Happy if you can support us by giving us a star! ⭐️

https://github.com/novuhq/novu
Nevo David
Nevo DavidOctober 11, 2022

Related Posts

How to

Building an Investor List App with Novu and Supabase

Building an Investor List App with Novu and Supabase

Prosper Otemuyiwa
Prosper OtemuyiwaMarch 15, 2024
How to

Implementing Internationalization in Apps: How to Translate Notifications

Implementing Internationalization in Apps: How to Translate Notifications

Prosper Otemuyiwa
Prosper OtemuyiwaMarch 1, 2024
How to

🔥 Building an email automation system with React Flow and Resend 🎉

Creating an email automation system to message people with a sequence of messages every 10 minutes.

Nevo David
Nevo DavidJuly 31, 2023