React Chat - Getting Started

jQuery
NOTE
Before you start the tutorial, ensure DevExtreme is installed in your application.
Angular
NOTE
Before you start the tutorial, ensure DevExtreme is installed in your application.
Vue
NOTE
Before you start the tutorial, ensure DevExtreme is installed in your application.
React
NOTE
Before you start the tutorial, ensure DevExtreme is installed in your application.

Chat is a UI component that allows users to send and receive messages in real time.

This tutorial shows how to add Chat to the page and configure the component's core settings.

Each section in this tutorial describes a single configuration step. You can also find the full source code in the following GitHub repository:

View on GitHub

Create a Chat

jQuery

Add DevExtreme to your jQuery application and use the following code to create a Chat component:

index.js
index.html
$(function() {
    $("#chat").dxChat({ });
});
<html>
    <head>
        <!-- ... -->
        <script type="text/javascript" src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
        <link rel="stylesheet" href="https://cdn3.devexpress.com/jslib/24.2.3/css/dx.light.css">
        <script type="text/javascript" src="https://cdn3.devexpress.com/jslib/24.2.3/js/dx.all.js"></script>
        <script type="text/javascript" src="index.js"></script>
    </head>
    <body>
        <div id="chat"></div>
    </body>
</html>
Angular

Add DevExtreme to your Angular application and use the following code to create a Chat component:

app.component.html
app.component.ts
app.module.ts
<dx-chat></dx-chat>
import { Component } from '@angular/core';

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
export class AppComponent {

}
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';

import { DxChatModule } from 'devextreme-angular';

@NgModule({
    declarations: [
        AppComponent
    ],
    imports: [
        BrowserModule,
        DxChatModule
    ],
    providers: [ ],
    bootstrap: [AppComponent]
})
export class AppModule { }
Vue

Add DevExtreme to your Vue application and use the following code to create a Chat component:

App.vue
<template>
    <DxChat />
</template>

<script setup>
import 'devextreme/dist/css/dx.light.css';
import { DxChat } from 'devextreme-vue/chat';
</script>
React

Add DevExtreme to your React application and use the following code to create a Chat component:

App.js
import React from 'react';

import 'devextreme/dist/css/dx.light.css';

import { Chat } from 'devextreme-react/chat';

function App() {
    return (
        <Chat />
    );
}

export default App;

To limit the Chat size, use the width and height properties:

jQuery
index.js
$(function() {
    $("#chat").dxChat({ 
        width: 400,
        height: 450,
    });
});
Angular
app.component.html
<dx-chat
    [width]="400"
    [height]="450"
>
</dx-chat>
Vue
App.vue
<template>
    <DxChat 
        width="400"
        height="450"
    />
</template>
React
App.js
function App() {
    return (
        <Chat
            width={400}
            height={450}
        />
    );
}

export default App;

Render Sent Messages

When a user enters a message in the Chat, the messageEntered event is raised. You can use this event handler to render the message you entered.

jQuery

In jQuery, the primary way to render a message is to call the renderMessage method:

index.js
$(function() {
    $("#chat").dxChat({ 
        // ...
        onMessageEntered: ({ component, message }) => {
            component.renderMessage(message);
        },
    });
});
Angular

In React, the primary way to render a new message is updating your items array or dataSource. This tutorial uses the items array:

app.component.html
app.component.ts
<dx-chat ...
    [items]="messages"
    (onMessageEntered)="onMessageEntered($event)"
>
</dx-chat>
import { DxChatTypes } from "devextreme-angular/ui/chat";
// ...
export class AppComponent {
    messages: DxChatTypes.Message[] = [];

    onMessageEntered({ message }) {
        this.messages = [...this.messages, message];
    }
}
Vue

In React, the primary way to render a new message is updating your items array or a dataSource. In this tutorial, the items array is used:

App.vue
<template>
    <DxChat ...
        :items="messages"
        @message-entered="onMessageEntered"
    />
</template>

<script setup>
import { ref } from "vue";
// ...

const messages = ref([]);
const onMessageEntered = ({ message }) => {
    messages.value = [...messages.value, message];
};
</script>
React

In React, the primary way to render a new message is updating your items array or a dataSource. In this tutorial, the items array is used:

App.js
import React, { useCallback, useState } from "react";
function App() {
    const [messages, setMessages] = useState([]);

    const onMessageEntered = useCallback(({ message }) => {
        setMessages((prevMessages) => [...prevMessages, message]);
    }, []);

    return (
        <Chat ...
            items={messages}
            onMessageEntered={onMessageEntered}
        />
    );
}

export default App;

Manage Users

Assign chat users:

  • Specify the user's ID.
  • Specify the user's name. If the name is not specified, it becomes "Unknown User".
  • Define avatars with a URL and alt text. If the URL is not specified, the avatar becomes the user's name initials.
  • Assign a user to the user property to define the chat owner.
jQuery
index.js
const firstUser = {
    id: "1",
    name: "User"
};

const secondUser = {
    id: "2",
    name: "Feedback Bot",
    avatarUrl: "./images/Chat/bot.png"
};

$(function() {
    $("#chat").dxChat({ 
        // ...
        user: firstUser,
    });
});
Angular
app.component.html
app.component.ts
<dx-chat ...
    [user]="firstUser"
>
</dx-chat>
import { DxChatTypes } from "devextreme-angular/ui/chat";
// ...
export class AppComponent {
    firstUser: DxChatTypes.User = {
        id: "1",
        name: "User",
    };
    secondUser: DxChatTypes.User = {
        id: "2",
        name: "Feedback Bot",
        avatarUrl: "./images/Chat/bot.png"
    };
}
Vue
App.vue
<template>
    <DxChat ...
        :user="firstUser"
    />
</template>

<script setup>
// ...
const firstUser = {
    id: "1",
    name: "User"
};

const secondUser = {
    id: "2",
    name: "Feedback Bot",
    avatarUrl: "./images/Chat/bot.png"
};
</script>
React
App.js
// ...
const firstUser = {
    id: "1",
    name: "User"
};

const secondUser = {
    id: "2",
    name: "Feedback Bot",
    avatarUrl: "./images/Chat/bot.png"
};

function App() {
    // ...
    return (
        <Chat ...
            user={firstUser}
        />
    );
}

export default App;

Set Initial Messages

If you want to specify initial messages in the Chat, use the items array.

jQuery
index.js
const initialMessages = [{
    timestamp: Date.now(),
    author: secondUser,
    text: "Hello! We'd love to hear your feedback. Please share your thoughts below!"
}];

$(function() {
    $("#chat").dxChat({ 
        // ...
        items: initialMessages,
    });
});
Angular
app.component.html
app.component.ts
<dx-chat ...
    [items]="messages"
>
</dx-chat>
import { DxChatTypes } from "devextreme-angular/ui/chat";
// ...
export class AppComponent {
    messages: DxChatTypes.Message[] = [{
        timestamp: Date.now(),
        author: secondUser,
        text: "Hello! We'd love to hear your feedback. Please share your thoughts below!"
    }];
}
Vue
App.vue
<template>
    <DxChat ...
        :items="messages"
    />
</template>

<script setup>
import { ref } from "vue";
// ...
const initialMessages = [{
    timestamp: Date.now(),
    author: secondUser,
    text: "Hello! We'd love to hear your feedback. Please share your thoughts below!"
}];

const messages = ref(initialMessages);
React
App.js
import React, { useState } from "react";

const initialMessages = [{
    timestamp: Date.now(),
    author: secondUser,
    text: "Hello! We'd love to hear your feedback. Please share your thoughts below!"
}];

function App() {
    const [messages, setMessages] = useState(initialMessages);

    return (
        <Chat ...
            items={messages}
        />
    );
}

export default App;

Post-Processing

Use onMessageEntered to perform message post processing (like sending the message to the server for storage). This tutorial simulates sending a message to a backend:

  1. The Feedback Bot user is added to the typingUsers array to show them typing.
  2. After one second, the typingUsers array is emptied, and Chat displays the answer message.
  3. After that, an alert is displayed, and Chat is disabled.
jQuery
index.js
$(function() {
    function sendToBackend() {
        setTimeout(() => {
            chat.option("typingUsers", []);
            chat.renderMessage({
                text: "Thanks for helping us improve!",
                author: secondUser,
                timestamp: Date.now()
            });
            chat.option("alerts", [{
                id: 1,
                message: "Session expired"
            }]);
            chat.option("disabled", true);
        }, 1000);
    }
    $("#chat").dxChat({ 
        // ...
        onMessageEntered: ({ component, message }) => {
            //...
            chat.option("typingUsers", [secondUser]);
            sendToBackend();
        },
    });
});
Angular
app.component.html
app.component.ts
<dx-chat ...
    [(alerts)]="alerts"
    [(disabled)]="disabled"
>
</dx-chat>
import { DxChatTypes } from "devextreme-angular/ui/chat";
// ...
export class AppComponent {
    messages: DxChatTypes.Message[] = [...];
    alerts: DxChatTypes.Alert[] = [];
    disabled: boolean = false;

    onMessageEntered({ message }) {
        // ...
        this.typingUsers = [this.secondUser];
        this.sendToBackend();
    }

    sendToBackend() {
        setTimeout(() => {
            this.typingUsers = [];
            this.messages = [
                ...this.messages,
                {
                    text: "Thanks for helping us improve!",
                    author: this.secondUser,
                    timestamp: Date.now(),
                },
            ];
            this.alerts = [
                ...this.alerts,
                {
                    id: 1,
                    message: "Session expired",
                },
            ];
            this.disabled = true;
        }, 1000);
    }
}
Vue
App.vue
<template>
    <DxChat ...
        v-model:alerts="alerts"
        v-model:disabled="disabled"
    />
</template>

<script setup>
import { ref } from "vue";
// ...

const messages = ref([]);
const alerts = ref([]);
const disabled = ref(false);

const onMessageEntered = ({ message }) => {
    // ...
    typingUsers.value = [secondUser];
    sendToBackend();
};

const sendToBackend = () => {
    setTimeout(() => {
        typingUsers.value = [];
        messages.value = [
            ...messages.value,
            {
                text: "Thanks for helping us improve!",
                author: secondUser,
                timestamp: Date.now(),
            },
        ];
        alerts.value = [
            ...alerts.value,
            {
                id: 1,
                message: "Session expired",
            },
        ];
        disabled.value = true;
    }, 1000);
};
</script>
React
App.js
import React, { useCallback, useState } from "react";
function App() {
    const [messages, setMessages] = useState([]);
    const [alerts, setAlerts] = useState([]);
    const [disabled, setDisabled] = useState(false);

    const onMessageEntered = useCallback(({ message }) => {
        // ...
        setTypingUsers([secondUser]);
        sendToBackend();
    }, []);

    const sendToBackend = () => {
        setTimeout(() => {
            setTypingUsers([]);
            setMessages((prevMessages) => [
                ...prevMessages,
                {
                    text: "Thanks for helping us improve!",
                    author: secondUser,
                    timestamp: Date.now(),
                },
            ]);
            setAlerts([
                {
                    id: 1,
                    message: "Session expired",
                },
            ]);
            setDisabled(true);
        }, 3000);
    };

    return (
        <Chat ...
            alerts={alerts}
            disabled={disabled}
        />
    );
}

export default App;