Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • React Tutorial
  • React Exercise
  • React Basic Concepts
  • React Components
  • React Props
  • React Hooks
  • React Router
  • React Advanced
  • React Examples
  • React Interview Questions
  • React Projects
  • Next.js Tutorial
  • React Bootstrap
  • React Material UI
  • React Ant Design
  • React Desktop
  • React Rebass
  • React Blueprint
  • JavaScript
  • Web Technology
Open In App
Next Article:
Project Idea | Collaborative Editor Framework in Real Time
Next article icon

Real-Time Collaborative Editing App using React & WebSockets

Last Updated : 13 Mar, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

This article will explain about real-time collaborative editor which can be updated by multiple users at the same time. It explains how to do it using a web socket for example - socket.io and react hooks such as useState() and useEffect().

Output Preview: Let us have a look at how the final output will look like.

Screenshot-2024-03-07-155711
OUTPUT PREVIEW IMAGE OF COLLABORATIVE EDITOR

Prerequisites:

  • JavaScript
  • React JS
  • useState() and useEffect() Hook in React
  • Socket.io

Approach to Create Real-Time Collaborative editor:

  • Initialize a new node.js project, install express and set up basic express server
  • Install socket.io for real time communication
  • Use socket.io event listeners to handle all connection and disconnection
  • Whenever there is any change in real time editor by client, broadcast it to all other clients
  • Implement event handlers to broadcast formatting changes to all the clients
  • Set up the new react app (steps are given below in this article)
  • Install socket-io.client to connect with the server made using socket.io
  • Implement a UI containing textarea and buttons for formatting and style
  • Use event handlers to manage the content updation in the editor
  • Wait for any updates from server and change the editor content accordingly
  • Update the styles of the editor based on the changes received from the server

Steps to create backend -

Step 1: Create backend folder

mkdir backend

Step 2: Change the directory

cd backend 

Step 3: Initialize the express app

npm init -y 

Step 4: Make server.js file for backend

In this file import all the dependencies and create the server using socket.io 

Step 5: Install the required dependencies for backend

npm install express cors socket.io nodemon 

Project Structure(Backend):

Screenshot-2024-03-08-154015
PROJECT STRUCTURE FOR BACKEND

Updated Dependencies in package.json file for backend:

"dependencies": {     "cors": "^2.8.5",     "express": "^4.18.3",     "nodemon": "^3.1.0",     "socket.io": "^4.7.4" } 

Example: Below is the code example:

JavaScript
// server.js (backend)  const express = require('express'); const http = require('http'); const socketIo = require('socket.io'); const cors = require('cors');  const app = express(); app.use(cors());  const server = http.createServer(app); const io = socketIo(server, {     cors: {         origin: '*',         methods: ['GET', 'POST'],         credentials: true     } });      io.on('connection', (socket) => {     console.log('New client connected');     socket.on('edit', (content) => {         io.emit('updateContent', content);     });      socket.on('bold', (bold) => {         io.emit('updateStyleBold', bold);     })      socket.on('italic', (italic) => {         io.emit('updateStyleItalic', italic);     })      socket.on('underline', (underline) => {         io.emit('updateStyleUnderline', underline);     })      socket.on('disconnect', () => {         console.log('Client disconnected');     }); });  const PORT = 5000; server.listen(PORT, () => console.log(`Server running on port ${PORT}`)); 

Steps to run backend:

nodemon server.js or node server.js 

Output:

Screenshot-2024-03-08-155659
OUTPUT OF BACKEND CODE

Steps to Create Frontend -

Step 1: Create react app

npx create-react-app frontend 

Step 2: Change the directory

cd frontend 

Step 3: Install all the dependencies

npm install socket-io.client 

Project Structure(Frontend):

Screenshot-2024-03-08-155150
PROJECT STRUCTURE FOR FRONTEND

Updated Dependencies in package.json for frontend -

"dependencies": {     "@testing-library/jest-dom": "^5.17.0",     "@testing-library/react": "^13.4.0",     "@testing-library/user-event": "^13.5.0",     "react": "^18.2.0",     "react-dom": "^18.2.0",     "react-scripts": "5.0.1",     "socket.io-client": "^4.7.4" }, 

Example: Below is the code example

CSS
.App {     display: flex;     flex-direction: column;     align-items: center;     padding: 20px;     font-family: Arial, sans-serif; }  h1 {     margin-bottom: 20px; }  .controls {     display: flex;     margin-bottom: 20px; }  .controls button {     margin-right: 10px;     padding: 5px 10px;     border: none;     border-radius: 5px;     background-color: darkslategray;     color: white;     cursor: pointer; }  .controls button:hover {     background-color: darkslategrey; }  .controls select, .controls input[type="color"] {     margin-right: 10px;     padding: 5px;     border: 1px solid #ccc;     border-radius: 5px; }  .controls select:focus, .controls input[type="color"]:focus {     outline: none;     border-color: #007bff; }  textarea {     width: 100%;     padding: 10px;     border: 1px solid #ccc;     border-radius: 5px;     font-size: 16px;     resize: vertical; }  textarea:focus {     outline: none;     border-color: cadetblue; } 
JavaScript
// App.js (frontend)  import React, {     useState,     useEffect } from 'react'; import io from 'socket.io-client'; import './App.css';  const socket = io('http://localhost:5000');  function App() {     const [content, setContent] = useState('');     const [bold, setBold] = useState(false);     const [italic, setItalic] = useState(false);     const [underline, setUnderline] = useState(false);     useEffect(() => {         socket.on('updateContent',             (updatedContent) => {                 setContent(updatedContent);             });          socket.on('updateStyleBold',             (bold) => {                 setBold(bold);             });          socket.on('updateStyleItalic',             (italic) => {                 setItalic(italic);             });          socket.on('updateStyleUnderline',             (underline) => {                 setUnderline(underline);             });          return () => {             socket.off('updateContent');         };     }, [bold, italic, underline]);      const handleEdit = (event) => {         const updatedContent = event.target.value;         setContent(updatedContent);         socket.emit('edit', updatedContent);     };      const handleBold = () => {         if (!bold) {             setBold(true);             socket.emit('bold', true);         }         else {             setBold(false);             socket.emit('bold', false);         }     }      const handleItalic = () => {         if (!italic) {             setItalic(true);             socket.emit('italic', true);         }         else {             setItalic(false);             socket.emit('italic', false);         }     }      const handleUnderline = () => {         if (!underline) {             setUnderline(true);             socket.emit('underline', true);         }         else {             setUnderline(false);             socket.emit('underline', false);         }     }       return (         <div className="App">             <h1>Real-time Collaborative Editor</h1>             <div className='controls'>                 <button onClick={() => handleBold()}>                     BOLD                 </button>                 <button onClick={() => handleItalic()}>                     ITALIC                 </button>                 <button onClick={() => handleUnderline()}>                     UNDERLINE                 </button>             </div>             <textarea                 value={content}                 onChange={handleEdit}                 rows={10}                 cols={50}                 style={{                     fontWeight: bold ? 'bold' : 'normal',                     fontStyle: italic ? 'italic' : 'normal',                     textDecoration: underline ? 'underline' : 'none'                 }}             />         </div>     ); }  export default App; 

Steps to Run Frontend:

npm start

Output:

outputgif
OUTPUT GIF FOR REAL-TIME COLLABORATIVE EDITOR

Next Article
Project Idea | Collaborative Editor Framework in Real Time
author
priya gupta 1
Improve
Article Tags :
  • Project
  • Web Technologies
  • ReactJS
  • Dev Scripter
  • React-Hooks
  • ReactJS-Projects
  • Dev Scripter 2024

Similar Reads

  • Real-time Updates with WebSockets and React Hooks
    The WebSocket protocol provides continuous, real-time, full-duplex communication between a client and server over a single TCP socket connection. The WebSocket protocol has only two plans: opening a handshake and facilitating data transfer. After the server receives the handshake request sent by the
    5 min read
  • Project Idea | Collaborative Editor Framework in Real Time
    NOTE: Most of the contents are taken from Project Report.So you can also download it from drop box links are given down in (Following additional topics may also be provided) Block . Simply you can read it out . Collaborative Editor Framework in Real Time Introduction: A collaborative editor is a for
    8 min read
  • Simple chat Application using Websockets with FastAPI
    In this article, we'll delve into the concept of WebSockets and their role in facilitating bidirectional communication between clients and servers. Subsequently, we'll embark on the journey of building a real-time multi-client chat application. This application will empower numerous users to connect
    6 min read
  • Create a Real-Time Weather Forecast App with React
    Real-time weather forecast app with React involves integrating with a weather API to fetch weather data and display it in the UI. Individuals can use the app to check the current weather conditions, temperature, humidity, and other relevant weather data for their location or any city they are intere
    5 min read
  • Real-Time Polling App with Node and React
    In this article, we’ll walk through the step-by-step process of creating a Real-Time Polling App using NodeJS, ExpressJS, and socket.io. This project will showcase how to set up a web application where users can perform real-time polling. Preview of final output: Let us have a look at how the final
    5 min read
  • Realtime chat app using Django
    Chat Room has been the most basic step toward creating real-time and live projects. The chat page that we will create will be a simple HTML boilerplate with a simple h1 text with the name of the current user and a link to log out to the user who is just logged in. You may need to comment on the line
    11 min read
  • Create a Video Editor using React
    Video Editor is one of the useful apps in day-to-day life. In this article, we’ll walk you through the process of building a basic video editing app using React Native. The application enables users to upload, trim, and convert specific scenes to GIFs and then download the final edited file directly
    6 min read
  • Create a News Reader app using React-Native
    Creating the News Reader application using React-Native language is an exciting project. Using this project, the users can read the news in the application itself, by filtering them according to the categories as per their interest. In this article, we will develop the complete News Reader applicati
    5 min read
  • Create a Text Editor App using React-Native
    In this article, we are going to implement a text editor app using React Native. It will contain multiple text formatting functionalities like bold, italic, underline, etc. We will implement Editor with a library called "react-native-pell-rich-editor." Preview of final output: Let us have a look at
    3 min read
  • Explain the Benefits and Challenges of Using WebSockets in Redux Applications.
    WebSockets provide a full-duplex communication channel over a single TCP connection, allowing for real-time, bidirectional communication between the client and server. When integrated with a Redux application, WebSockets can enable continuous data updates and improve user experience by providing rea
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences