Skip to content

SahilAggarwal2004/react-peer-chat

Repository files navigation

react-peer-chat

A simple-to-use React component for implementing peer-to-peer chatting, powered by peerjs.

Features

  • Peer-to-peer chat without requiring knowledge of WebRTC
  • Easy integration
  • Supports persistent text chat across page reloads
  • Recovers old chats upon reconnection
  • Option to clear chat on command
  • Supports audio/voice chat with automatic mixing for multiple peers
  • Multiple peer connections. See multi-peer usage
  • Automatic reconnection handling for network interruptions
  • Fully customizable. See usage with FaC

Installation

To install react-peer-chat:

  # with npm:
  npm install react-peer-chat --save

  # with yarn:
  yarn add react-peer-chat

  # with pnpm:
  pnpm add react-peer-chat

  # with bun:
  bun add react-peer-chat

Usage

react-peer-chat provides two primary methods to integrate chat functionality into your React apps: through the <Chat> component and the useChat hook.

It also exports a clearChat function that clears the text chat from the browser's session storage when called.

Chat Component

The default export of react-peer-chat is the <Chat> component, which offers the easiest integration and is fully configurable. When using the <Chat> component, the user will initially see two buttons (SVG icons) - one for text chat and the other for voice chat.

Basic Usage

import React from "react";
import Chat, { clearChat } from "react-peer-chat";
import "react-peer-chat/style.css";

export default function App() {
  return (
    <div>
      <Chat name="John Doe" peerId="my-unique-id" remotePeerId="remote-unique-id" />
      {/* Text chat will be cleared when following button is clicked. */}
      <button onClick={clearChat}>Clear Chat</button>
    </div>
  );
}

Multi Peer Usage

import React from "react";
import Chat, { clearChat } from "react-peer-chat";
import "react-peer-chat/style.css";

export default function App() {
  return (
    <div>
      <Chat
        name="John Doe"
        peerId="my-unique-id"
        remotePeerId={["remote-unique-id-1", "remote-unique-id-2", "remote-unique-id-3"]} // Array of remote peer ids
      />
      {/* Text chat will be cleared when following button is clicked. */}
      <button onClick={clearChat}>Clear Chat</button>
    </div>
  );
}

Note: The remotePeerId prop is read at mount and whenever peerId changes. Changes to remotePeerId alone (without peerId changing) won't establish new connections. In peer-to-peer chat scenarios, new peers should connect to existing peers by providing their IDs at mount time, rather than existing peers updating this prop dynamically.

Partial Customization

Use the props provided by the <Chat> component for customization.

import React from "react";
import Chat from "react-peer-chat";
import "react-peer-chat/style.css";

export default function App() {
  return (
    <Chat
      name="John Doe"
      peerId="my-unique-id"
      remotePeerId="remote-unique-id"
      dialogOptions={{
        position: "left",
        style: { padding: "4px" },
      }}
      props={{ title: "React Peer Chat Component" }}
      onError={(error) => console.error("Fatal error:", error)}
      onPeerError={(error) => console.error("Peer error:", error.type, error)}
      onNetworkError={(error) => console.log("Reconnecting...")}
    />
  );
}

Full Customization

Use Function as Children (FaC) to fully customize the <Chat> component.

import React from 'react'
import Chat from 'react-peer-chat'

export default function App() {
    return <Chat
        name='John Doe'
        peerId='my-unique-id'
        remotePeerId='remote-unique-id'
        onError={(error) => console.error('Fatal error:', error)}
        onPeerError={(error) => console.error('Peer error:', error.type, error)}
    >
        {({ remotePeers, messages, sendMessage, audio, setAudio }) => (
            <YourCustomComponent>
                {...}
            </YourCustomComponent>
        )}
    </Chat>
}

Custom ICE Servers

You can also provide custom ICE servers to avoid connectivity issues if the free TURN server provided by react-peer-chat expires.

import React from "react";
import Chat from "react-peer-chat";
import "react-peer-chat/style.css";

export default function App() {
  return (
    <Chat
      name="John Doe"
      peerId="my-unique-id"
      remotePeerId="remote-unique-id"
      peerOptions={{
        config: {
          iceServers: [
            { urls: "stun:stun-server.example.com:19302" },
            {
              urls: "turn:turn-server.example.com:19403",
              username: "optional-username",
              credential: "auth-token",
            },
          ],
        },
        // other peerjs options (optional)
      }}
    />
  );
}

useChat Hook

The useChat hook is ideal when you want to completely redesign the Chat UI.

Basic Usage

import React, { useEffect, useRef, useState } from "react";
import { clearChat, useChat } from "react-peer-chat";
import { BiSolidMessageDetail, BiSolidMessageX, BsFillMicFill, BsFillMicMuteFill, GrSend } from "react-peer-chat/icons";
import "react-peer-chat/style.css";

function Chat({ text = true, audio = true, onMessageReceived, dialogOptions, props = {}, children, ...hookProps }) {
  const {
    peerId, // Complete peer ID
    remotePeers, // Object mapping remote peer IDs to their names
    messages, // Array of all chat messages
    sendMessage, // Function to send a message to all connected peers
    audio: audioEnabled, // Current audio state (enabled/disabled)
    setAudio, // Function to toggle audio on/off (only works if audio option is set to true)
  } = useChat({
    text,
    audio,
    onMessageReceived: modifiedOnMessageReceived,
    ...hookProps,
  });
  const containerRef = useRef(null);
  const [dialog, setDialog] = useState(false);
  const dialogRef = useRef(null);
  const inputRef = useRef(null);
  const [notification, setNotification] = useState(false);

  function modifiedOnMessageReceived(message) {
    if (!dialogRef.current?.open) setNotification(true);
    onMessageReceived?.(message);
  }

  useEffect(() => {
    if (dialog) dialogRef.current?.show();
    else dialogRef.current?.close();
  }, [dialog]);

  useEffect(() => {
    const container = containerRef.current;
    if (container) container.scrollTop = container.scrollHeight;
  }, [dialog, remotePeers, messages]);

  return (
    <div className="rpc-main-container rpc-font" {...props}>
      {typeof children === "function" ? (
        children({ remotePeers, messages, sendMessage, audio: audioEnabled, setAudio })
      ) : (
        <>
          {text && (
            <div className="rpc-dialog-container">
              {dialog ? (
                <BiSolidMessageX title="Close chat" onClick={() => setDialog(false)} />
              ) : (
                <div className="rpc-notification">
                  <BiSolidMessageDetail
                    title="Open chat"
                    onClick={() => {
                      setNotification(false);
                      setDialog(true);
                    }}
                  />
                  {notification && <span className="rpc-badge" />}
                </div>
              )}
              <dialog ref={dialogRef} className={`${dialog ? "rpc-dialog" : ""} rpc-position-${dialogOptions?.position || "center"}`} style={dialogOptions?.style}>
                <div className="rpc-heading">Chat</div>
                <hr className="rpc-hr" />
                <div>
                  <div ref={containerRef} className="rpc-message-container">
                    {messages.map(({ id, text }, i) => (
                      <div key={i}>
                        <strong>{id === peerId ? "You" : remotePeers[id]}: </strong>
                        <span>{text}</span>
                      </div>
                    ))}
                  </div>
                  <hr className="rpc-hr" />
                  <form
                    className="rpc-input-container"
                    onSubmit={(e) => {
                      e.preventDefault();
                      const text = inputRef.current?.value;
                      if (text) {
                        inputRef.current.value = "";
                        sendMessage({ id: peerId, text });
                      }
                    }}
                  >
                    <input ref={inputRef} className="rpc-input rpc-font" placeholder="Enter a message" />
                    <button type="submit" className="rpc-button">
                      <GrSend title="Send message" />
                    </button>
                  </form>
                </div>
              </dialog>
            </div>
          )}
          {audio && (
            <button className="rpc-button" onClick={() => setAudio(!audioEnabled)}>
              {audioEnabled ? <BsFillMicFill title="Turn mic off" /> : <BsFillMicMuteFill title="Turn mic on" />}
            </button>
          )}
        </>
      )}
    </div>
  );
}

export default function App() {
  return (
    <div>
      <Chat name="John Doe" peerId="my-unique-id" remotePeerId="remote-unique-id" />
      {/* Text chat will be cleared when following button is clicked. */}
      <button onClick={clearChat}>Clear Chat</button>
    </div>
  );
}

API Reference

useChat Hook

Here is the full API for the useChat hook, these options can be passed as parameters to the hook:

Parameter Type Required Default Description
name string No Anonymous User Name of the peer which will be shown to the remote peer.
peerId string Yes - It is the unique id that is alloted to a peer. It uniquely identifies a peer from other peers.
remotePeerId string | string[] No - Unique id(s) of remote peer(s) to connect to. Read at mount and when peerId changes; changes to this prop alone won't create new connections.
text boolean No true Text chat will be enabled if this property is set to true.
recoverChat boolean No false Old chats will be recovered upon reconnecting with the same peer(s).
audio boolean No true Voice chat will be enabled if this property is set to true. Audio from multiple peers is automatically mixed.
peerOptions PeerOptions No - Options to customize peerjs Peer instance.
onError ErrorHandler No console.error Function to be executed for fatal errors (browser not supported, microphone not accessible).
onPeerError PeerErrorHandler No console.error Function to be executed for all peer runtime errors. The library automatically handles reconnection for network errors.
onNetworkError PeerErrorHandler No - Function to be executed for network/server errors (which trigger automatic reconnection). Useful for showing "reconnecting..." UI.
onMessageSent MessageEventHandler No - Function to be executed when a text message is sent to other peers.
onMessageReceived MessageEventHandler No - Function to be executed when a text message is received from other peers.

Chat Component

Here is the full API for the <Chat> component, these properties can be set on an instance of <Chat>. It contains all the parameters that are listed in useChat Hook API Reference along with the following parameters:

Parameter Type Required Default Description
dialogOptions DialogOptions No { position: 'center' } Options to customize text dialog box styling.
props DivProps No - Props to customize the <Chat> component.
children Children No - See usage with FaC

Types

Children

import type { ReactNode, SetStateAction } from "react";

type RemotePeers = Record<string, string>;
type Message = {
  id: string;
  text: string;
};
type ChildrenOptions = {
  remotePeers: RemotePeers;
  messages: Message[];
  sendMessage: (message: Message) => void;
  audio: boolean;
  setAudio: (value: SetStateAction<boolean>) => void;
};
type Children = (childrenOptions: ChildrenOptions) => ReactNode;

DialogOptions

import type { CSSProperties } from "react";

type DialogPosition = "left" | "center" | "right";
type DialogOptions = {
  position?: DialogPosition;
  style?: CSSProperties;
};

DivProps

import type { DetailedHTMLProps, HTMLAttributes } from "react";

type DivProps = DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>;

ErrorHandler

type ErrorHandler = (error: Error) => void;

PeerErrorHandler

import type { PeerError, PeerErrorType } from "peerjs";

export type PeerErrorHandler = ErrorHandler<PeerError<`${PeerErrorType}`>>;

MessageEventHandler

type Message = {
  id: string;
  text: string;
};
type MessageEventHandler = (message: Message) => void;

PeerOptions

import type { PeerOptions } from "peerjs";

License

This project is licensed under the MIT License

Packages

 
 
 

Contributors