React Chat Markdown Content VisualizationPremium
Display formatted markdown content directly in Chat messages. Users can view tables, code snippets, and other formatted text as part of the conversation flow, making technical discussions more accessible and engaging.
Setup
To display markdown content inside the Chat messages interface, follow these steps:
1. Install a markdown parsing library
This example uses the marked library to parse markdown and the DOMPurify library to sanitize the resulting HTML:
Note: KendoReact is not affiliated with the marked or DOMPurify libraries. You can use any markdown parsing and HTML sanitizing libraries that fit your project requirements.
npm install marked dompurify
2. Create a function to parse markdown content
To render markdown content in Chat messages, you need to parse the markdown text into HTML and sanitize it before rendering. Create a function that uses the marked library to convert markdown strings into HTML and DOMPurify to remove unsafe markup:
import { setOptions } from 'marked';
import DOMPurify from 'dompurify';
const parseMarkdown = (text: string): string => {
const parser = setOptions({});
// Bot or AI text can contain raw HTML, so sanitize it to prevent XSS.
return DOMPurify.sanitize(parser.parse(text || '') as string);
};
3. Use the messageTemplate to render markdown content
Define a MessageTemplate function to render markdown content in messages. This function checks if the message is from the user or the bot and renders the content accordingly:
const MessageTemplate = (props: ChatMessageTemplateProps) => {
const message = props.item as AppMessage;
const isUser = message.author?.id === user.id;
if (isUser) {
return (
<div className="k-chat-bubble k-bubble">
<div className="k-bubble-content">
<span className="k-chat-bubble-text">{message.text}</span>
</div>
</div>
);
}
const htmlContent = parseMarkdown(message.text || '');
return (
<div className="k-chat-bubble k-bubble">
<div className="k-bubble-content">
<div dangerouslySetInnerHTML={{ __html: htmlContent }} />
</div>
</div>
);
};
<Chat
messages={messages}
authorId={user.id}
messageTemplate={MessageTemplate}
/>