@vkruglikov/react-telegram-web-app

repository·master·Indexed 20 days ago

https://github.com/vkruglikov/react-telegram-web-app

A collection of React components and hooks for Telegram Mini Apps that abstracts the Telegram WebApp JavaScript API. It provides tools to manage native UI elements like the MainButton, BackButton, and SettingsButton, as well as hooks for haptic feedback, cloud storage, QR code scanning, theme parameters, and initialization data. Version 2.2.0 supports React ^18.

Tokens
11.8K
Snippets
42
Records
72
Agent score
68%

What's inside @vkruglikov/react-telegram-web-app

  1. Overview of @vkruglikov/react-telegram-web-app

    master
    The @vkruglikov/react-telegram-web-app package provides a set of React components, hooks, and type definitions to simplify building Telegram Mini Apps. It abstracts the Telegram WebApp JavaScript API into a React-friendly interface, allowing you to manage UI elements like the Back Button and Main Button, access user data, and trigger native Telegram features like Haptic Feedback or Cloud Storage using hooks and components.
  2. Access WebApp Initialization Data

    master

    The library provides access to the initialization data passed by Telegram.

    InitDataUnsafe

    This object contains the raw data from the Telegram WebApp initialization. Key fields include:

    • user: A WebAppUser object containing user details (id, first_name, username, etc.).
    • chat: A WebAppChat object if the app is launched from a chat.
    • auth_date: The timestamp of the data.
    • hash: The validation hash.
    • query_id: The unique query ID.
    • start_param: The start parameter used to launch the app.

    InitData

    InitData is the raw string representation of the initialization data.

  3. Understand the ThemeParams interface

    master
    The ThemeParams interface provides an object containing the user's current Telegram theme settings. It is a direct implementation of the original Telegram WebApp ThemeParams type. This allows your React application to access and react to the user's specific color preferences (such as background, button, and text colors) as defined by their Telegram client.
  4. Set up local HTTPS with mkcert

    master

    To run the demo locally with HTTPS (required for many Telegram Mini App features), use mkcert to generate a certificate for your local domain.

    1. Run the following command to create a certificate:
      mkcert react-telegram-web-app.domain
    2. Map the domain to your local machine by adding it to your /etc/hosts file:
      127.0.0.1 react-telegram-web-app.domain
    mkcert react-telegram-web-app.domain
  5. Configure WebAppProvider Options

    master

    When using WebAppProvider, you can pass an Options object to customize behavior.

    OptionTypeDescription
    asyncbooleanEnables asynchronous mode.
    smoothButtonsTransitionbooleanWhen true, enables smooth transitions for MainButton and BackButton during show()/hide() calls to prevent flickering. Default: false
    smoothButtonsTransitionMsnumberDuration of the transition in milliseconds. Default: 10
  6. Example: Show a popup with MainButton

    master

    This example demonstrates how to use MainButton and the useShowPopup hook together to trigger a native Telegram popup when a button is clicked.

    import { MainButton, useShowPopup } from '@vkruglikov/react-telegram-web-app';
    
    const Content = () => {
      const showPopup = useShowPopup();
    
      const handleClick = () =>
        showPopup({
          message: 'Hello, I am popup',
        });
    
      return <MainButton text="SHOW POPUP" onClick={handleClick} />;
    };
  7. Show native popups with useShowPopup

    master

    The useShowPopup hook provides a function to display a native Telegram popup.

    Returns: ShowPopupFunction which accepts ShowPopupParams.

    import { useShowPopup } from '@vkruglikov/react-telegram-web-app';
    
    const showPopup = useShowPopup();
    
    showPopup({ message: 'Hello world' }).then(buttonId => console.log(buttonId));
  8. Access initialization data with useInitData

    master

    The useInitData hook provides access to the Telegram initialization data.

    Returns a tuple containing:

    • initDataUnsafe: undefined | InitDataUnsafe
    • initData: undefined | string (the raw init data string)
    import { useInitData } from '@vkruglikov/react-telegram-web-app';
    
    const [initDataUnsafe, initData] = useInitData();
  9. Use the useCloudStorage hook

    master

    The useCloudStorage hook provides access to the Telegram CloudStorage object using Promise-based functions, eliminating the need to manually pass callbacks. It allows you to persist data in the user's Telegram cloud.

    Returns an object containing:

    • getItem: GetItemFunction
    • getItems: GetItemsFunction
    • getKeys: GetKeysFunction
    • removeItem: RemoveItemFunction
    • setItem: SetItemFunction
    // Note: Specific implementation details for GetItemFunction etc. are in their respective documentation
    const { getItem, setItem } = useCloudStorage();
  10. Configure the MainButton component via MainButtonProps

    master

    The MainButton component accepts the following props to control the Telegram MiniApp's main action button:

    PropTypeDefaultDescription
    colorstringthemeParams.button_colorThe background color of the button.
    disabledbooleanfalseWhether the button is interactive or disabled.
    onClick() => voidNoneThe callback function triggered when the button is pressed.
    progressbooleanfalseIf true, shows a progress indicator on the button.
    textstring'CONTINUE'The label displayed on the button.
    textColorstringthemeParams.button_text_colorThe color of the button text.
    <MainButton
      text="Submit"
      color="#ff0000"
      textColor="#ffffff"
      disabled={false}
      progress={false}
      onClick={() => console.log('Button clicked!')}
    />