Build an Application Like Google Docs Using React and MongoDB
Last Updated :
15 May, 2024
In this article, we will create applications like Google Docs Made In React and MongoDB. This project basically implements functional components and manages the state accordingly. The user uses particular tools and format their document like Google Docs and save their work as well. The logic of Google Docs is implemented using JSX and Quill.
Preview of Final Output:
Build an Application Like Google Docs Made In React and MongoDBPrerequisites:
Approach To Build a Docs Application Using React and MongoDB
For a Backend App
- index.js: Sets up Socket.IO server, handles client connections, and defines event listeners for "get-document", "send-changes", and "save-document". It interacts with MongoDB through controllers.
- documentSchema.js: Defines MongoDB schema for documents with
_id
and data
fields. - db.js: Establishes MongoDB connection using Mongoose.
- document-controller.js: Provides functions to interact with MongoDB.
getDocument
retrieves or creates a document by ID. updateDocument
updates a document with new data.
For a Frontend App
- App.js: Manages routing and initial document creation, directing users to a unique document editor page upon visiting the root URL.
- Editor.jsx: Implements a document editor interface using Quill.js and manages real-time collaboration through Socket.IO. Handles document loading, content changes, and autosave functionality.
Steps to Create the Backend App And Installing Module
Step 1: Create directory for project.
mkdir Google-Docs-Clone
Step 2: Create sub directories for frontend and backend.
mkdir clientmkdir server
Step 3: Open backend directory using the following command.
cd server
Step 4: Initialize Node Package Manager using the following command.
npm init
Step 5: Install socket.io mongoose and dotenv package in backend using the following command.
npm install socket.io mongoose dotenv
Project Structure:
Project Structure
The updated dependencies in package.json for backend will look like:
"dependencies": {
"dotenv": "^16.0.0",
"mongoose": "^6.1.6",
"socket.io": "^4.4.1"
}
JavaScript
//index.js
import { Server } from 'socket.io';
import Connection from './database/db.js';
import {
getDocument,
updateDocument
} from './controller/document-controller.js'
const PORT = process.env.PORT || 9000;
Connection();
const io = new Server(PORT, {
cors: {
origin: '*',
methods: ['GET', 'POST']
}
});
io.on('connection', socket => {
socket.on('get-document', async documentId => {
const document = await getDocument(documentId);
socket.join(documentId);
socket.emit('load-document', document.data);
socket.on('send-changes', delta => {
socket.broadcast.to(documentId).emit(
'receive-changes', delta);
})
socket.on('save-document', async data => {
await updateDocument(documentId, data);
})
})
});
JavaScript
//documentShema.js
import mongoose from 'mongoose';
const documentSchema = mongoose.Schema({
_id: {
type: String,
required: true
},
data: {
type: Object,
required: true
}
});
const document = mongoose.model('document', documentSchema);
export default document;
JavaScript
//db.js
import mongoose from 'mongoose';
const Connection = async () => {
const URL = `TOUR DB URL HERE`;
try {
await mongoose.connect(URL);
console.log('Database connected successfully');
} catch (error) {
console.log('Error while connecting with the database ', error);
}
}
export default Connection;
JavaScript
//document-controller.js
import Document from '../schema/documentSchema.js'
export const getDocument = async (id) => {
if (id === null) return;
const document = await Document.findById(id);
if (document) return document;
return await Document.create({ _id: id, data: "" })
}
export const updateDocument = async (id, data) => {
return await Document.findByIdAndUpdate(id, { data });
}
Start your backend app using the following command:
node index.js
Steps To Create the Frontend App And Installing Module
Step 1: Open frontend directory using the following command.
cd client
Step 2: Create react application in the current directory using the following command.
npx create-react-app google-docs-clone
Step 3: Install socket.io-client , react-router-dom, quill and uuid package in client using the following command.
npm install socket.io-client react-router-dom quill uuid
Step 3: Open Google-Docs-Clone using your familiar code editor.
If you are using VS code editor, run the following command open VS code in current folder.
code .
Project Structure:
Project Structure
The updated dependencies in package.json for frontend will look like:
"dependencies": {
"@emotion/react": "^11.7.1",
"@emotion/styled": "^11.6.0",
"@mui/material": "^5.2.8",
"@testing-library/jest-dom": "^5.16.1",
"@testing-library/react": "^12.1.2",
"@testing-library/user-event": "^13.5.0",
"quill": "^1.3.7",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-router-dom": "^6.2.1",
"react-scripts": "5.0.0",
"socket.io-client": "^4.4.1",
"uuid": "^8.3.2",
"web-vitals": "^2.1.3"
}
Example : Below is an example to Build an Application Like Google Docs Made In React.
HTML
<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
</body>
</html>
CSS
/* App.css */
.container {
width: 60%;
background: #FFF;
box-shadow: 0 0 5px 0 rgba(0, 0, 0, 0.5);
margin: 10px auto 10px auto !important;
min-height: 100vh;
}
.ql-toolbar.ql-snow {
display: flex;
justify-content: center;
position: sticky;
top: 0;
z-index: 1;
background: #F3F3F3;
border: none !important;
box-shadow: 0 0 5px 0 rgba(0, 0, 0, 0.5);
}
JavaScript
//App.js
import './App.css';
import {
BrowserRouter as Router,
Routes,
Route,
Navigate
} from 'react-router-dom';
import { v4 as uuid } from 'uuid';
import Editor from './component/Editor.js';
function App() {
return (
<Router>
<Routes>
<Route path='/' element={
<Navigate replace to={`/docs/${uuid()}`} />} />
<Route path='/docs/:id' element={<Editor />} />
</Routes>
</Router>
);
}
export default App;
JavaScript
//Editor.jsx
import { useEffect, useState } from 'react';
import Quill from 'quill';
import 'quill/dist/quill.snow.css';
import { Box } from '@mui/material';
import styled from '@emotion/styled';
import { io } from 'socket.io-client';
import { useParams } from 'react-router-dom';
const Component = styled.div`
background: #F5F5F5;
`
const toolbarOptions = [
['bold', 'italic', 'underline', 'strike'],
['blockquote', 'code-block'],
[{ 'header': 1 }, { 'header': 2 }],
[{ 'list': 'ordered' }, { 'list': 'bullet' }],
[{ 'script': 'sub' }, { 'script': 'super' }],
[{ 'indent': '-1' }, { 'indent': '+1' }],
[{ 'direction': 'rtl' }],
[{ 'size': ['small', false, 'large', 'huge'] }],
[{ 'header': [1, 2, 3, 4, 5, 6, false] }],
[{ 'color': [] }, { 'background': [] }],
[{ 'font': [] }],
[{ 'align': [] }],
['clean']
];
const Editor = () => {
const [socket, setSocket] = useState();
const [quill, setQuill] = useState();
const { id } = useParams();
useEffect(() => {
const quillServer = new Quill('#container',
{
theme: 'snow',
modules: { toolbar: toolbarOptions }
});
quillServer.disable();
quillServer.setText('Loading the document...')
setQuill(quillServer);
}, []);
useEffect(() => {
const socketServer = io('http://localhost:9000');
setSocket(socketServer);
return () => {
socketServer.disconnect();
}
}, [])
useEffect(() => {
if (socket === null || quill === null) return;
const handleChange = (delta, oldData, source) => {
if (source !== 'user') return;
socket.emit('send-changes', delta);
}
quill && quill.on('text-change', handleChange);
return () => {
quill && quill.off('text-change', handleChange);
}
}, [quill, socket])
useEffect(() => {
if (socket === null || quill === null) return;
const handleChange = (delta) => {
quill.updateContents(delta);
}
socket && socket.on('receive-changes', handleChange);
return () => {
socket && socket.off('receive-changes', handleChange);
}
}, [quill, socket]);
useEffect(() => {
if (quill === null || socket === null) return;
socket && socket.once('load-document', document => {
quill.setContents(document);
quill.enable();
})
socket && socket.emit('get-document', id);
}, [quill, socket, id]);
useEffect(() => {
if (socket === null || quill === null) return;
const interval = setInterval(() => {
socket.emit('save-document', quill.getContents())
}, 2000);
return () => {
clearInterval(interval);
}
}, [socket, quill]);
return (
<Component>
<Box className='container' id='container'></Box>
</Component>
)
}
export default Editor;
JavaScript
//index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
Start your frontend app using the following command:
npm start
Open the browser and navigate to the following link to open the application.
http://localhost:3000/
Output:
Google Docs Using React and Mongodb
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Steady State Response In this article, we are going to discuss the steady-state response. We will see what is steady state response in Time domain analysis. We will then discuss some of the standard test signals used in finding the response of a response. We also discuss the first-order response for different signals. We
9 min read
JavaScript Interview Questions and Answers JavaScript (JS) is the most popular lightweight, scripting, and interpreted programming language. JavaScript is well-known as a scripting language for web pages, mobile apps, web servers, and many other platforms. Both front-end and back-end developers need to have a strong command of JavaScript, as
15+ min read
React Tutorial React is a JavaScript Library known for front-end development (or user interface). It is popular due to its component-based architecture, Single Page Applications (SPAs), and Virtual DOM for building web applications that are fast, efficient, and scalable.Applications are built using reusable compon
8 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read