4. Integrating GenAI into Your Website

Building the Chatbot Interface

  1. Install Chat UI Kit:

    npm install @chatscope/chat-ui-kit-react
  2. Implement the Chat UI:

    • In src/App.js:

    import { useState } from 'react';
    import { MainContainer, ChatContainer, MessageList, Message, MessageInput, TypingIndicator } from "@chatscope/chat-ui-kit-react";
    import "@chatscope/chat-ui-kit-styles/dist/default/styles.min.css";
    
    function App() {
      const [messages, setMessages] = useState([{ message: "Hello! How can I assist you?", sender: "ChatGPT", direction: "incoming" }]);
      const [typing, setTyping] = useState(false);
    
      const handleSend = async (message) => {
        const newMessage = { message, sender: "user", direction: "outgoing" };
        setMessages([...messages, newMessage]);
        setTyping(true);
    
        // Call to backend (your server's /chat endpoint)
        const response = await fetch('/chat', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({ message })
        });
        const data = await response.json();
    
        setMessages([...messages, newMessage, { message: data.choices[0].message.content, sender: "ChatGPT", direction: "incoming" }]);
        setTyping(false);
      };
    
      return (
        <MainContainer>
          <ChatContainer>
            <MessageList typingIndicator={typing ? <TypingIndicator content="ChatGPT is typing..." /> : null}>
              {messages.map((msg, index) => <Message key={index} model={msg} />)}
            </MessageList>
            <MessageInput placeholder="Type a message..." onSend={handleSend} />
          </ChatContainer>
        </MainContainer>
      );
    }
    
    export default App;

After all the modification, your front end should look like this:

Connecting to Your Backend

  • Update the fetch URL to point to your backend server if it’s running on a different port.

Last updated