1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

ReactでChatGPTのような機能を実装するためのライブラリ「chat-ui-kit-react」について

Posted at

以前、開発プロジェクトでchatGPTのようなチャット機能を独自Webアプリケーション上に実装したことがあり、その際に使用させていただいた「chat-ui-kit-react」というライブラリが非常に使いやすく適していたのでご紹介させていただきます。

公式リファレンス:
https://chatscope.io/storybook/react/?path=/docs/documentation-introduction--docs

このライブラリを使えば以下のようなチャット機能が簡単に実装可能です。
image.png

使用方法

npmの場合以下のコマンドでインストール可能です。

# 機能
npm install @chatscope/chat-ui-kit-react
# デザイン
npm install @chatscope/chat-ui-kit-styles

とりあえず簡単に実装してみると以下のようになります。
これで先ほどの画面が実装できます。

import {
  MainContainer,
  ChatContainer,
  MessageList,
  Message,
  MessageInput,
} from "@chatscope/chat-ui-kit-react";
import "@chatscope/chat-ui-kit-styles/dist/default/styles.min.css";
import "./chat.css";

const HOME = () => {
  return (
    <div className="chat">
      <MainContainer>
        <ChatContainer>
          <MessageList>
            <Message
              model={{
                message: "こんにちは!",
                direction: "incoming",
                position: "single",
              }}
            />
            <Message
              model={{
                message: "はじめまして!",
                direction: "outgoing",
                position: "single",
              }}
            />
            <Message
              model={{
                message: "よろしくお願いします!",
                direction: "outgoing",
                position: "single",
              }}
            />
            <Message
              model={{
                message: "こちらこそよろしくお願いします!",
                direction: "incoming",
                position: "single",
              }}
            />
          </MessageList>
          <MessageInput placeholder="Type message here" />
        </ChatContainer>
      </MainContainer>
    </div>
  );
};

export default HOME;

詳しく解説していきます。
まずメッセージ部分の記述が以下になります。

<MessageList>
    <Message
      model={{
        message: "こんにちは!",
        direction: "incoming",
        position: "single",
      }}
    />
</MessageList>

MessageListの中のMessageが1通のメッセージとなっております。
modelの各パラメータは以下の通りです。

パラメータ 解説 入力可能値
message メッセージのテキスト string
sentTime 送信時間 string
sender 送信者 string
direction incomingが相手からのメッセージ(左側表示)
outgoingがこっちからのメッセージ(右側表示)
'incoming' / 'outgoing' / 0 / 1
position メッセージの吹き出し形 'single' / 'first' / 'normal' / 'last' / 0 / 1 / 2 / 3
type メッセージの種類 'html' / 'text' / 'image' / 'custom'
payload データの方 string / object / allowedChildren([MessageCustomContent])

メッセージの入力欄はMessageInputとなっております。

<MessageInput placeholder="Type message here" />

以下のようにすることで送信時のfunctionを定義することができます。

<MessageInput
    placeholder="Type message here"
    onSend={onSendMessage} 
    onChange={onInputChange} 
    value={inputMessage} 
/>

メッセージの部分を配列から取得するようにし、それをstateで管理することによりメッセージの送信機能を実装できます。
以下が最終的な実装になります

import {
  MainContainer,
  ChatContainer,
  MessageList,
  Message,
  MessageInput,
} from "@chatscope/chat-ui-kit-react";
import "@chatscope/chat-ui-kit-styles/dist/default/styles.min.css";
import "./chat.css";
import { useState } from "react";

type ChatMessage = {
  message: string;
  sentTime: string;
  direction: number;
};

const DUMMY_MESSAGES: ChatMessage[] = [
  {
    message: "こんにちは!",
    sentTime: "2023-10-01T10:00:00Z",
    direction: 0,
  },
  {
    message: "はじめまして!",
    sentTime: "2023-10-01T10:01:00Z",
    direction: 1,
  },
  {
    message: "よろしくお願いします!",
    sentTime: "2023-10-01T10:02:00Z",
    direction: 0,
  },
];

const HOME = () => {
  const [inputMessage, setInputMessage] = useState("");
  const [messages, setMessages] = useState<ChatMessage[]>(DUMMY_MESSAGES);

  const handleSendMessage = () => {
    if (inputMessage.trim()) {
      const newMessage: ChatMessage = {
        message: inputMessage,
        sentTime: new Date().toISOString(),
        direction: 1,
      };
      setMessages([...messages, newMessage]);
      setInputMessage("");
    }
  };

  return (
    <div className="chat">
      <MainContainer>
        <ChatContainer>
          <MessageList>
            {messages.map((msg, index) => (
              <Message
                model={{
                  message: msg.message,
                  sentTime: msg.sentTime,
                  direction: msg.direction === 0 ? "incoming" : "outgoing",
                  position: "single",
                }}
                key={index}
              />
            ))}
          </MessageList>
          <MessageInput
            placeholder="Type message here"
            onSend={handleSendMessage}
            onChange={setInputMessage}
            value={inputMessage}
          />
        </ChatContainer>
      </MainContainer>
    </div>
  );
};

export default HOME;

今回はフロントエンドのみの実装ですが、メッセージをDBで管理、メッセージ送信時にバックエンドから応答メッセージを生成するようにすればchatGPTのようなチャットアプリを作ることができます。
他にもいろいろな機能がありそうなのでぜひ試してみてください。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?