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
How to Build Note Taking Application using Node.js?
Building a note-taking application using Node.js involves several steps, from setting up the server to managing the application logic and user interface. This guide will walk you through the process of creating a simple note-taking application using Node.js, Express, and a few other key technologies
6 min read
Chat Application using React Hooks and Firebase
In the era of technology messaging apps have become an aspect of our everyday routines enabling us to engage and interact with others promptly. For developers interested in crafting their messaging app leveraging React Hooks in conjunction, with Firebase presents a strategy, for constructing a dynam
6 min read
How To Build a Basic CRUD App With Node and React ?
In this article, we will explore how to build a simple CRUD (Create, Read, Update, Delete) application using Node.js for the backend and React for the frontend. Additionally, we will integrate MongoDB as the database to store our data.Preview of final output:App functionalityCreate a new student (CR
11 min read
Build an Online Code Compiler using React.js and Node.js
In this article, we will learn how to build an online code compiler using React.js as frontend and Express.js as backend. Users will be able to write C, C++, Python, and Java code with proper syntax highlighting as well as compile and execute it online. The main objective of building an online compi
7 min read
Designing a Markdown note taking application in ReactJS
In this article, we will learn how to design a Markdown note-taking application in React that can help one to quickly jot down notes and download the rendered output. The use of Markdown allows one to spend less time on formatting the text and therefore create rich text content using only the Markdo
4 min read
Google SignIn using Firebase Authentication in ReactJS
Firebase simplifies mobile and web app development by offering pre-built features like user authentication (email/password, Google Sign-In, etc.) without the need to build complex backends. This saves time and resources for developers.In this article, we will discuss about the Google Sign-In feature
5 min read
Freelancer Portfolio Builder Application using MERN Stack
In today's digital age, having a professional portfolio is essential for freelancers to showcase their skills and attract potential clients. In this article, we'll dive into the process of building a Freelancer Portfolio Builder using the MERN (MongoDB, Express.js, React.js, Node.js) stack. This pro
5 min read
How to Insert a Document into a MongoDB Collection using Node.js?
MongoDB, a popular NoSQL database, offers flexibility and scalability for handling data. If you're developing a Node.js application and need to interact with MongoDB, one of the fundamental operations you'll perform is inserting a document into a collection. This article provides a step-by-step guid
5 min read
Deployment of React Application using GitHub Pages
Deploying a React application using GitHub Pages is an easy and efficient way to host your projects online for free. In this article, we will walk you through the steps to deploy your React app, making it accessible to users with a live URL. PrerequisitesA GitHub accountNode.js and npm installedBasi
4 min read
Deploy a React Application with AWS
AWS is a subsidiary of Amazon & offers a broad range of cloud computing services, which means services using their infrastructure which is hosted on various data centers all over the world which we can rent to run our own solutions. In this article, we will learn how to deploy a React applicatio
4 min read