Skip to content

@telegram-apps/sdk-react@2

React.js package providing utilities that developers may find useful when developing a mini application.

TIP

Since this package offers utility functions that extend the functionality of @telegram-apps/sdk, it is recommended to review the SDK package documentation first.

Installation

Before proceeding, it is assumed that you have already installed the react package, as it is a peer dependency of this package.

bash
pnpm i @telegram-apps/sdk-react
bash
npm i @telegram-apps/sdk-react
bash
yarn add @telegram-apps/sdk-react

INFO

This package fully re-exports the @telegram-apps/sdk package, so you don't need to install it separately.

Usage

Here is a simple usage example of the package:

tsx
import ReactDOM from 'react-dom/client';
import { init, backButton } from '@telegram-apps/sdk-react';

import { BackButton } from './BackButton.js';

// Initialize the package.
init();

// Mount the Back Button, so we will work with 
// the actual component properties.
backButton.mount();

ReactDOM
  .createRoot(document.getElementById('root')!)
  .render(<BackButton/>);
ts
import { useEffect } from 'react';
import { backButton, useSignal } from '@telegram-apps/sdk-react';

/**
 * Component which controls the Back Button visibility.
 */
export function BackButton() {
  const isVisible = useSignal(backButton.isVisible);

  useEffect(() => {
    console.log('The button is', isVisible ? 'visible' : 'invisible');
  }, [isVisible]);

  useEffect(() => {
    backButton.show();
    return () => {
      backButton.hide();
    };
  }, []);

  return null;
}

Hooks

useSignal

A helper that allows a developer to use our signals in the application.

It returns the underlying value and updates it whenever the signal value changes.

ts
import { useEffect } from 'react';
import { backButton, useSignal } from '@telegram-apps/sdk-react';

function Component() {
  const isVisible = useSignal(backButton.isVisible);

  useEffect(() => {
    console.log('The button is', isVisible ? 'visible' : 'invisible');
  }, [isVisible]);

  useEffect(() => {
    backButton.show();
    return () => {
      backButton.hide();
    };
  }, []);

  return null;
}

useLaunchParams

A function that returns the mini application's launch parameters.

tsx
import { useLaunchParams } from '@telegram-apps/sdk-react';

function Component() {
  const lp = useLaunchParams();
  return <div>Start parameter: {lp.startParam}</div>;
}

Released under the MIT License.