Search code examples
javascripthtmlreactjswidgettelegram

Telegram Login widget doesn't render in React SPA app


I have a React frontend app (was bootstraped by create-react-app) and django at the backend. We have dev and production environments, they have different domains. Now I attempt to implement widget at dev env.

I want to login users via telegram login widget. I follow official core telegram docs. But button doesn't render at login page though there is the script into DOM tree

I try to move script to <body> in index.html outside div root where is mounting React, but behaviour was the same. No errors in console

enter image description here


Solution

  • This is the first time we encountered the same problem

    We tried to add the widget script directly to the JSX component, but nothing happens

    Solved this problem by creating a script element in the useEffect hook (or can be in componentDidMount):

    1. Created a ref where the Telegram iframe widget will be inserted:

    // Refs
    const telegramWrapperRef = useRef<HTMLDivElement>(null);
    
    ...
    
    return (
        <div ref={telegramWrapperRef}></div>
    );

    1. Defined the creation of the script element in useEffect:

    useEffect(() => {
      const scriptElement = document.createElement('script');
      scriptElement.src = 'https://telegram.org/js/telegram-widget.js?22';
      scriptElement.setAttribute('data-telegram-login', 'paste-bot-name');
      scriptElement.setAttribute('data-size', 'large');
      scriptElement.setAttribute('data-auth-url', 'paste-redirect-url');
      scriptElement.async = true;
    
      telegramWrapperRef.current.appendChild(scriptElement);
    }, []);

    1. After that everything will work

    I should note that on localhost it will also be noticeable, because the error "Bot domain invalid" will be displayed at the place of widget insertion (inside telegramWrapperRef)

    To make it work properly, you need to deploy it with HTTPS.