Search code examples
htmlreactjsreact-reduxbotframeworkmarkdown

BotFramework-Webchat Middleware for renderMarkdown


I'd like to add renderMarkdown using the React component in the Bot framework. I am able to add through HTML like below and it's working as expected but my requirement is to add the same feature using the react.

<!DOCTYPE html>
<html>
   <head>
      <script src="https://cdn.botframework.com/botframework-webchat/latest/webchat.js"></script>
      <script src="https://www.acai-hub.com/js/markdown-it.min-8.4.2.js"></script>
      <style>
         html,
         body {
            height: 100%;
         }

         body {
            margin: 0;
         }

         #webchat {
            height: 100%;
            width: 100%;
         }
      </style>
   </head>
   <body>
      <div id="webchat" role="main"></div>
      <script>
        const markdownIt = window.markdownit({ html: true, linkify: true, typographer: true });
        const renderMarkdown = text => markdownIt.render(text);
         window.WebChat.renderWebChat(
            {
               directLine: window.WebChat.createDirectLine({
                  token: 'VeY8HxuBVIw.fKAVwOjeVn9tcx7fhZ0cSCBz5vM8tp8G0JcNT3BGiRI'
               }),
               userID: 'Arun',
               username: 'Arun',
               locale: 'en-US',
               botAvatarInitials: 'WC',
               userAvatarInitials: 'WW',
               renderMarkdown: renderMarkdown
            },
            document.getElementById('webchat')
         );
      </script>
   </body>
</html>

Does anybody know how to add renderMarkdown using middleware since I am new to the react?


Solution

  • This works for me. Markdown including Emoji support :-) In webchat.js

    import React, { useEffect, useMemo } from 'react';
    import ReactWebChat, { createDirectLine, createStyleSet } from 'botframework-webchat';
    import './WebChat.css';
    // emoji support
    var md = require('markdown-it')();
    var emoji = require('markdown-it-emoji');
    md.use(emoji);
    
    const WebChat = ({ className, onFetchToken, store, token }) => {
      const directLine = useMemo(() => createDirectLine({ token }), [token]);
    
      const styleSet = useMemo(
        () =>
          createStyleSet({
                rootWidth: '100%',
          }),
        []
      );
    
      useEffect(() => {
        onFetchToken();
      }, [onFetchToken]);
    
      return token ? (
        <ReactWebChat className={`${className || ''} web-chat`} directLine={directLine} renderMarkdown={ md.render.bind(md) } store={store} styleSet={styleSet} />
      ) : (
        <div className={`${className || ''} connect-spinner`}>
          <div className="content">
            <div className="icon">
              <span className="ms-Icon ms-Icon--Robot" />
            </div>
            <p>Please wait while we are connecting.</p>
          </div>
        </div>
      );
    };
    
    export default WebChat;