Skip to content

React

We provide React hooks to make it easy to integrate EZChat into your React application.

Installation

npm install @ezchat/frontend

Usage

1. Import useEzChatRoomConnection

import { useEzChatRoomConnection } from "@ezchat/frontend/react";

2. Auth Function

The authFunction is an async function that returns a token for the user to connect to the room. It is called every time the user connects to the room. The token is used to authenticate the user to the room. The function should return a string that is the token. Example:

authFunction: async () => {
    const ret = await fetch("<your server>/ezchat/access-token");
    return (await ret.json())["token"];
}

3. Use the hook in your component

const ezchat = useEzChatRoomConnection(
    4213, // room id
    {
    authFunction: authFunction
    },
);

useEzChatRoomConnection takes two arguments, a room id (number) and a config object with the following properties:

Property Type Description
authFunction async function a function that returns a token for the user to connect to the room. This will usually just be a fetch to your backend
reverseMessages boolean a boolean that determines if the messages should be reversed (default: false)

useEzChatRoomConnections properties

The useEzChatRoomConnection hook returns an object with the following properties:

Property Type Description
sendMessage (message: string) => void a function that sends a message to the room
fetchMoreMessages (amount: number) => void a function that fetches more messages from the room
refreshToken () => void a function that refreshes the token
connected boolean a boolean that determines if the user is connected to the room
loading boolean a boolean that determines if the user is currently connecting to the room
error Error an error object that contains the error message if the user fails to connect to the room
messages Message[] an array of messages in the room
hasMoreMessages boolean a boolean that determines if there are more messages to fetch
fetchMoreMessages function a function that fetches more messages from the room
isLoadingMoreMessages boolean a boolean that determines if the user is currently fetching more messages
loadMoreMessagesError Error an error object that contains the error message if the user fails to fetch more messages

React Provider (Optional)

The ezchat-js react package also contains an optional provider that can be used to provide the auth function to all the components in your app. This is useful if you want to use the same auth function in multiple components.

Usage

import { EzChatProvider } from "@ezchat/frontend/react";

function App() {
    return (
        <EzChatProvider
            authFunction={}
        >
            <RestOfYourSiteGoesHere />
        </EzChatProvider>
    );
}

When set up like this, you can use useEzChatRoomConnection in any component in your app without having to pass the auth function as a prop.

Example

import React from 'react';
import { useEZChat } from '@ezchat/frontend';

function Chat() {
    const [inputValue, setInputValue] = useState("");

    const ezchat = useEzChatRoomConnection(3, {
        authFunction: async () => {
            const ret = await fetch("localhost:5858/ezchat/access-token");
            return (await ret.json())["token"];
        },
    });

    const handleSubmit = async () => {
        ezchat.sendMessage(inputValue);
        setInputValue("");
    };

    return (
        <>
            <div>
                <h2>
                    connected: {ezchat.connected.toString()} loading: {ezchat.loading.toString()} error: {ezchat.error?.message.toString()}
                </h2>
                <p>-------------------------------------------------------------------------------------------------</p>
                <div className="messagelist">
                    {ezchat?.messages.map((message) => (
                        <p>
                            {message.chatter?.name || "anonymous"}: {message.messageText}
                        </p>
                    ))}
                    {ezchat.hasMoreMessages && (
                        <button onClick={() => ezchat.fetchMoreMessages()}>load more messages</button>
                    )}
                </div>
                <input
                    type="text"
                    value={inputValue}
                    onChange={(e) => setInputValue(e.target.value)}
                    onSubmit={handleSubmit}
                />
                <button onClick={handleSubmit} type="submit">
                    Send
                </button>
            </div>
        </>
    );
}