Open In App

Build an Application Like Google Docs Using React and MongoDB

Last Updated : 15 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

Docs Application using React Preview
Build an Application Like Google Docs Made In React and MongoDB

Prerequisites:

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:
google
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:

google1
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:

Docs Application using react and mongo
Google Docs Using React and Mongodb

Next Article

Similar Reads