Skip to content

Using React with MassiveRealm

React is a popular open-source JavaScript library for building user interfaces.

You can use MassiveRealm with React to create real-time applications such as chat apps, collaborative tools, and multiplayer games.

Getting started

Check out our Quick Start Guide to create a new MassiveRealm project and get your API key.

Prerequisites:

  • Create a new MassiveRealm project.
  • Your project's URL and Public Key will be sent to your email.
  • Create Logic entry.
  • Create Room entry with alias chat-room.

MassiveRealm Server Setup

Step 1: Create Model

Navigate to the Communication > Models section in your project's logic and create a new model called Message with the following fields:

  • time - String
  • sessionId - String
  • text - String

Model: Message

Step 2: Create Server Command

Navigate to the Communication > Server section in your project's logic.

Create a new command called BroadcastMessage with the following input parameters:

  • text - String

This command will broadcast a message to all clients in the room, except the sender.

Server: Broadcast Message

Add the following code to the command:

javascript
let message = {
    time: (new Date()).toLocaleTimeString(),
    sessionId: $session.id,
    text: $params.text
};

$session.broadcast('NewMessage', { message });

Server: Broadcast Message

Step 3: Create Client Commands

Navigate to the Communication > Client section in your project's logic. Here we will create 3 commands:

Command 1: NewMessage

Input Parameters:

  • message - Type: "Model: Message"

Client: NewMessage

Command 2: UserJoined

Input Parameters:

  • sessionId - String

Client: NewMessage

Command 3: UserLeft

Input Parameters:

  • sessionId - String

Client: NewMessage

Step 4: Hooks

Navigate to the Communication > Hooks section in your project's logic.

Hook 1: OnRoomJoin

Broadcast a message to all clients when a client joins the room.

javascript
$session.broadcast('UserJoined', {
    sessionId: $session.id
});

Hooks: OnRoomJoin

Hook 2: OnRoomLeave

Broadcast a message to all clients when a client leaves the room.

javascript
$session.broadcast('UserLeft', {
    sessionId: $session.id
});

Hooks: OnRoomJoin

Set Up Your React Project

Step 1: Create a React App

  1. Create a React App:

    bash
    npx create-react-app massiverealm-chat
    cd massiverealm-chat
  2. Install MassiveRealm Client SDK:

    bash
    npm install massiverealm-client

Step 2: Create the UI

  1. Update App.js:

    jsx
    import React, { useState } from 'react';
    import { Client as MassiveRealmClient } from 'massiverealm-client';
    
    function App() {
      const [mrClient, setMrClient] = useState(null);
      const [connected, setConnected] = useState(false);
      const [joined, setJoined] = useState(false);
      const [logs, setLogs] = useState([]);
      const [roomId, setRoomId] = useState('room-1');
    
      const appendLog = (message) => {
        setLogs((prevLogs) => [...prevLogs, message]);
      };
    
      const connect = () => {
        const client = new MassiveRealmClient({
          debug: true,
    
          // Replace with your project URL
          url: 'https://your-project-url/',
    
          // Replace with your public key
          publicKey: 'your-public-key',
    
          onConnect: () => {
            appendLog('Connected');
            setConnected(true);
          },
    
          onDisconnect: () => {
            appendLog('Disconnected');
            setConnected(false);
            setJoined(false);
          },
    
          onJoinRoom: () => {
            appendLog(`Joined room ${roomId}`);
            setJoined(true);
          },
    
          onLeaveRoom: () => {
            appendLog(`Left room ${roomId}`);
            setJoined(false);
          },
    
          onCommand: (command, data) => {
            appendLog(`Received command: ${command} with data: ${JSON.stringify(data)}`);
          },
    
          onError: (error) => {
            appendLog(`Error: ${error}`);
          },
        });
    
        client.connect();
        setMrClient(client);
      };
    
      const disconnect = () => {
        if (mrClient) {
          mrClient.disconnect();
          setMrClient(null);
        }
      };
    
      const joinRoom = () => {
        if (mrClient) {
          mrClient.joinRoom({
            alias: 'chat-room',
            id: roomId
          });
        }
      };
    
      return (
        <div className="App">
          <button onClick={connect} disabled={connected}>Connect</button>
          <button onClick={disconnect} disabled={!connected}>Disconnect</button>
          <input
            type="text"
            value={roomId}
            onChange={(e) => setRoomId(e.target.value)}
            disabled={!connected}
          />
          <button onClick={joinRoom} disabled={!connected || joined}>Join Room</button>
          <div id="logs">
            {logs.map((log, index) => (
              <div key={index}>{log}</div>
            ))}
          </div>
        </div>
      );
    }
    
    export default App;
  2. Add Basic Styling (Optional):

    css
    /* Add this to App.css */
    .App {
      text-align: center;
    }
    #logs {
      margin-top: 20px;
      text-align: left;
      height: 200px;
      overflow-y: scroll;
      border: 1px solid #ccc;
      padding: 10px;
    }
    .App button {
      margin: 5px;
    }
    .App input {
      margin: 5px;
    }

Step 3: Test the Application

  1. Run Your React App:

    bash
    npm start
  2. Connect and Interact:

    • Click the Connect button.
    • After connecting, enter a room ID or use the default room-1, and click Join Room.
    • Observe the logs for connection, room joining, and disconnection events.

By following these steps, you should have a basic chat application that connects to a MassiveRealm server, joins a room, and logs connection events.

Optimization Tip

Storing room settings on the client side may significantly reduce network traffic. This way, the client will not need to request the room settings each time it joins a room.

Navigate to the Rooms section and select the room you want to optimize. Then click on Export on the left side and copy the code.

Optimization Code JSON

Paste that JSON into the client-side code, and you're done!

jsx
 ...
 const client = new MassiveRealmClient({
   debug: true,

   // Replace with your project URL
   url: 'https://your-project-url/',

   // Replace with your public key
   publicKey: 'your-public-key',

   roomConfig: { 
     'chat-room': {"serverCommands":{"BroadcastMessage":{"id":10,"params":[{"name":"commandId","type":"uint8"},{"name":"text","type":"string8"}]}},"clientCommands":{"UserLeft":{"id":10,"params":[{"name":"commandId","type":"uint8"},{"name":"sessionId","type":"string8"}]},"UserJoined":{"id":11,"params":[{"name":"commandId","type":"uint8"},{"name":"sessionId","type":"string8"}]},"NewMessage":{"id":12,"params":[{"name":"commandId","type":"uint8"},{"name":"message","type":"model:Message"}]}},"models":{"Message":{"params":[{"name":"time","type":"string8"},{"name":"sessionId","type":"string8"},{"name":"text","type":"string8"}]}}} 
   }, 

   onConnect: () => {
     appendLog('Connected');
     setConnected(true);
   },
   ...
 });
 ...

More Performance Tips.