@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.
pnpm i @telegram-apps/sdk-react
npm i @telegram-apps/sdk-react
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:
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/>);
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.
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.
import { useLaunchParams } from '@telegram-apps/sdk-react';
function Component() {
const lp = useLaunchParams();
return <div>Start parameter: {lp.startParam}</div>;
}