This guide will walk you through the process of rendering markdown messages in your React application using the useLopusChat hook. We’ll cover the setup, rendering logic, and best practices to ensure a smooth integration.

Prequisites

  1. Ensure you have a React application setup
  2. Complete the quickstart guide
  3. Install react-markdown package
npm install react-markdown

Upgrade Your Message Component with ReactMarkdown

Return messages inside a ReactMarkdown component instead of a div:

import React, { ReactElement, JSXElementConstructor } from 'react';
import ReactMarkdown from 'react-markdown';

export function Message({ message }: MessageProps) {
  return (
    <div
      className={`mb-2 p-2 rounded ${
        message.sender === 'USER'
          ? 'bg-blue-600 text-white ml-auto'
          : 'bg-gray-200 text-black'
      } max-w-[80%]`}
    >
      {(() => {
        switch (typeof message.content) {
          case 'string':
            return (
              <ReactMarkdown className="prose max-w-none">
                {message.content}
              </ReactMarkdown>
            );
          case 'object':
            if (React.isValidElement(message.content)) {
              return message.content;
            }
            return <div>{JSON.stringify(message.content)}</div>;
          default:
            return (
              <ReactMarkdown className="prose max-w-none">
                {String(message.content)}
              </ReactMarkdown>
            );
        }
      })()}
    </div>
  );
} 

interface Message {
  content: string | ReactElement<unknown, string | JSXElementConstructor<any>> | Record<string, unknown>;
  sender: 'USER' | 'ASSISTANT';
}

interface MessageProps {
  message: Message;
}

Your Lopus Chat Component can now render markdown messages:

Lopus Chat Component

Best Practices

  1. Type Safety: Use type guards like isReceivedMessage to safely handle different message types.
  2. Error Handling: Wrap sendQuery and sendSubmission calls in try-catch blocks to manage errors effectively.
  3. Component Handling: For messages containing components, ensure they are rendered correctly.
  4. Cleanup: The hook manages cleanup automatically, but ensure to remove any custom message handlers if added.

By following these steps, you can effectively render markdown messages in your React application using the useLopusChat hook. This setup allows for a rich, interactive chat experience.