### Development Server Output Example
Source: https://github.com/telegram-mini-apps/reactjs-template/blob/master/README.md
Example output from the development server indicating local and network URLs. Use the 'Local' link to view the application in your browser.
```Bash
VITE v5.2.12 ready in 237 ms
➜ Local: https://localhost:5173/reactjs-template
➜ Network: https://172.18.16.1:5173/reactjs-template
➜ Network: https://172.19.32.1:5173/reactjs-template
➜ Network: https://192.168.0.171:5173/reactjs-template
➜ press h + enter to show help
```
--------------------------------
### Install Project Dependencies
Source: https://github.com/telegram-mini-apps/reactjs-template/blob/master/README.md
Install the project dependencies using npm. This command is essential after cloning the template.
```Bash
npm install
```
--------------------------------
### InitDataPage Example Usage
Source: https://github.com/telegram-mini-apps/reactjs-template/blob/master/_autodocs/api-reference/pages.md
Illustrates how InitDataPage displays Telegram init data, including raw and parsed states, user, receiver, and chat information. Shows example output format.
```typescript
import { InitDataPage } from '@/pages/InitDataPage';
import { useSignal } from '@tma.js/sdk-react';
// The page displays data like:
// Init Data:
// raw: "user=..."
// auth_date: "2024-01-01T12:00:00.000Z"
// hash: "abc123..."
//
// User:
// id: "123456789"
// first_name: "John"
// last_name: "Doe"
// username: "johndoe"
```
--------------------------------
### EnvUnsupported Component Example Usage
Source: https://github.com/telegram-mini-apps/reactjs-template/blob/master/_autodocs/api-reference/components.md
Shows how to render the EnvUnsupported component when launch parameters cannot be retrieved.
```typescript
import { EnvUnsupported } from '@/components/EnvUnsupported';
// In main entry point
try {
const launchParams = retrieveLaunchParams();
// ... initialize app
} catch (e) {
root.render();
}
```
--------------------------------
### RGB Component Example Usage
Source: https://github.com/telegram-mini-apps/reactjs-template/blob/master/_autodocs/api-reference/components.md
Demonstrates how to use the RGB component with different color values and CSS classes.
```typescript
import { RGB } from '@/components/RGB/RGB';
export const ColorDisplay = () => {
return (
);
};
```
--------------------------------
### Route Array Example
Source: https://github.com/telegram-mini-apps/reactjs-template/blob/master/_autodocs/types.md
An example of how to define an array of Route objects for application navigation. Each object specifies the path, component, and optional display properties for a route.
```typescript
import { type Route } from '@/navigation/routes';
const customRoutes: Route[] = [
{
path: '/',
Component: HomePage,
title: 'Home',
},
{
path: '/about',
Component: AboutPage,
title: 'About',
},
{
path: '/settings',
Component: SettingsPage,
title: 'Settings',
icon: ,
},
];
```
--------------------------------
### DisplayDataRow Example Usage
Source: https://github.com/telegram-mini-apps/reactjs-template/blob/master/_autodocs/types.md
Provides an example of creating an array of DisplayDataRow objects, including both data and link variants.
```typescript
import { type DisplayDataRow } from '@/components/DisplayData/DisplayData';
const rows: DisplayDataRow[] = [
// Data rows
{ title: 'Name', value: 'John Doe' },
{ title: 'Active', value: true },
{ title: 'Score', value: 95 },
// Link rows
{ title: 'Profile', type: 'link', value: '/profile' },
{ title: 'Website', type: 'link', value: 'https://example.com' },
// Empty value
{ title: 'Bio', value: undefined },
];
```
--------------------------------
### Initialization Module (init.ts) Side Effects
Source: https://github.com/telegram-mini-apps/reactjs-template/blob/master/_autodocs/architecture.md
Outlines the side effects performed by the initialization module, such as SDK setup and component mounting.
```text
- Initializes @tma.js/sdk-react
- Mounts components (backButton, initData, miniApp, etc.)
- Binds CSS variables from theme and viewport
```
--------------------------------
### Example Usage of isRecord
Source: https://github.com/telegram-mini-apps/reactjs-template/blob/master/_autodocs/api-reference/utilities.md
Provides various examples of calling isRecord with different data types to illustrate its behavior and return values. It also shows its use in conditional logic for safe property access.
```typescript
import { isRecord } from '@/css/classnames';
isRecord({}) // true
isRecord({ key: 'value' }) // true
isRecord(new Date()) // true (plain object)
isRecord([]) // false (array)
isRecord(null) // false (not truthy)
isRecord(undefined) // false (not truthy)
isRecord('string') // false (not object)
isRecord(123) // false (not object)
// In conditional logic
const config: unknown = parseConfig();
if (isRecord(config)) {
// Safe to access properties
const apiUrl = config.apiUrl;
const debug = config.debug;
}
```
--------------------------------
### IndexPage Example Usage
Source: https://github.com/telegram-mini-apps/reactjs-template/blob/master/_autodocs/api-reference/pages.md
Demonstrates how to import and include the IndexPage component in React Router routes.
```typescript
import { IndexPage } from '@/pages/IndexPage/IndexPage';
import { Route } from 'react-router-dom';
export const routes = [
{ path: '/', Component: IndexPage },
// ... other routes
];
```
--------------------------------
### Run Development Server with HTTPS
Source: https://github.com/telegram-mini-apps/reactjs-template/blob/master/README.md
Start the application in development mode using HTTPS. This command may prompt for a sudo password to configure SSL certificates.
```Bash
npm run dev:https
```
--------------------------------
### Running Development Server
Source: https://github.com/telegram-mini-apps/reactjs-template/blob/master/_autodocs/README.md
Commands to start the development server. Use `npm run dev` for an HTTP server or `npm run dev:https` for an HTTPS server, which may require sudo privileges on the first run.
```bash
npm run dev # HTTP server
npm run dev:https # HTTPS server (requires sudo first time)
```
--------------------------------
### Root Component Setup
Source: https://github.com/telegram-mini-apps/reactjs-template/blob/master/_autodocs/api-reference/components.md
The Root component initializes the application with error handling and TON Connect UI provider. It's the top-level wrapper for the entire app.
```typescript
export function Root(): JSX.Element
```
```typescript
import { Root } from '@/components/Root';
import ReactDOM from 'react-dom/client';
const root = ReactDOM.createRoot(document.getElementById('root')!);
root.render();
```
--------------------------------
### Run a Script
Source: https://github.com/telegram-mini-apps/reactjs-template/blob/master/README.md
Execute project scripts using the 'npm run' command. For example, to build the application, use 'npm run build'.
```Bash
npm run {script}
# Example: npm run build
```
--------------------------------
### DisplayData Component Usage Example
Source: https://github.com/telegram-mini-apps/reactjs-template/blob/master/_autodocs/types.md
Shows how to use the DisplayData component with its props, including a header, footer, and an array of data rows.
```typescript
import { DisplayData, type DisplayDataProps } from '@/components/DisplayData/DisplayData';
const props: DisplayDataProps = {
header: 'User Information',
footer: 'Last updated: 2024-01-01',
rows: [
{ title: 'Email', value: 'user@example.com' },
{ title: 'Phone', value: '+1234567890' },
],
};
export const UserSection = () => ;
```
--------------------------------
### Page Navigation with Link and useNavigate
Source: https://github.com/telegram-mini-apps/reactjs-template/blob/master/_autodocs/README.md
Provides examples for navigating between pages using the 'Link' component (preferred) and the 'useNavigate' hook. Ensure 'Link' and 'useNavigate' are imported from the appropriate routing library.
```typescript
// Via Link (preferred)
Go
// Via navigate hook
const navigate = useNavigate();
navigate('/init-data');
```
--------------------------------
### CSS BEM Example
Source: https://github.com/telegram-mini-apps/reactjs-template/blob/master/_autodocs/api-reference/utilities.md
Illustrates Block, Element, Modifier (BEM) naming conventions for CSS classes.
```css
.card { /* block */ }
.card--active { /* modifier */ }
.card__title { /* element */ }
.card__title--bold { /* element with modifier */ }
.card__content { /* element */ }
.card__content--primary { /* element with modifier */ }
.card__action { /* element */ }
.card__action--disabled { /* element with modifier */ }
```
--------------------------------
### Navigation Integration Example
Source: https://github.com/telegram-mini-apps/reactjs-template/blob/master/_autodocs/types.md
Demonstrates how to integrate the defined routes into a React application using React Router's Routes and Route components. Includes a fallback route for unmatched paths.
```typescript
{routes.map((route) => (
))}
} />
```
--------------------------------
### Display Launch Parameters
Source: https://github.com/telegram-mini-apps/reactjs-template/blob/master/_autodocs/api-reference/pages.md
This snippet shows how to import and display launch parameters within a React component. It retrieves platform, version, settings visibility, bot inline status, and start parameters.
```typescript
import {
LaunchParamsPage
} from '@/pages/LaunchParamsPage';
// Page displays data like:
// tgWebAppPlatform: "tdesktop"
// tgWebAppVersion: "8.4"
// tgWebAppShowSettings: true
// tgWebAppBotInline: false
// tgWebAppStartParam: ""
// tgWebAppData: [Link] Open
// tgWebAppThemeParams: [Link] Open
```
--------------------------------
### Initialize Telegram Mini Apps SDK
Source: https://github.com/telegram-mini-apps/reactjs-template/blob/master/_autodocs/api-reference/init.md
Example of how to initialize the Telegram Mini Apps SDK using the `init` function. It configures debug mode, Eruda, and macOS workarounds based on development environment and platform.
```typescript
import { init } from '@/init.ts';
import { retrieveLaunchParams } from '@tma.js/sdk-react';
const launchParams = retrieveLaunchParams();
const platform = launchParams.tgWebAppPlatform;
const debug = import.meta.env.DEV;
await init({
debug: debug,
eruda: debug && ['ios', 'android'].includes(platform),
mockForMacOS: platform === 'macos',
});
```
--------------------------------
### BEM Block Function Examples
Source: https://github.com/telegram-mini-apps/reactjs-template/blob/master/_autodocs/api-reference/utilities.md
Demonstrates how to use the BlockFn returned by the BEM utility to generate class names for a block with various modifier types.
```typescript
const [b, e] = bem('card');
b() // Returns: 'card'
b('active') // Returns: 'card card--active'
b({ active: true, disabled: false }) // Returns: 'card card--active'
b(['active', 'large']) // Returns: 'card card--active card--large'
```
--------------------------------
### TON Connect Page Example Usage
Source: https://github.com/telegram-mini-apps/reactjs-template/blob/master/_autodocs/api-reference/pages.md
Demonstrates the rendering of the TON Connect Button in both disconnected and connected states. Shows the expected UI elements and data display for wallet connection status, account details, and device information.
```typescript
import { TONConnectPage } from '@/pages/TONConnectPage/TONConnectPage';
// Disconnected:
// [TON Connect Button]
// "To display the data related to the TON Connect,
// it is required to connect your wallet"
// Connected:
// [Wallet Logo] Tonkeeper
// Tonkeeper
//
// Account:
// Address: EQC...
// Chain: -239 (mainnet)
// Public Key: abc123...
//
// Device:
// App Name: Tonkeeper
// App Version: 5.2.0
// Max Protocol Version: 4
// Platform: ios
// Features: ton_proof, ...
```
--------------------------------
### ErrorBoundary Usage Example
Source: https://github.com/telegram-mini-apps/reactjs-template/blob/master/_autodocs/types.md
Demonstrates how to use the ErrorBoundary component with custom props, including a fallback UI.
```typescript
import { ErrorBoundary, type ErrorBoundaryProps } from '@/components/ErrorBoundary';
function MyErrorFallback({ error }: { error: unknown }) {
return
Error: {String(error)}
;
}
const props: ErrorBoundaryProps = {
children: ,
fallback: MyErrorFallback,
};
export function Root() {
return ;
}
```
--------------------------------
### Environment Mocking for Development
Source: https://github.com/telegram-mini-apps/reactjs-template/blob/master/_autodocs/README.md
This example demonstrates how to mock the Telegram environment during development using `mockEnv.ts`. It allows for simulating Telegram events and parameters without a live Telegram client, which is automatically applied in development mode.
```typescript
// Automatically applied in development (import.meta.env.DEV)
mockTelegramEnv({
onEvent(e) {
if (e.name === 'web_app_request_theme') {
// Respond with mock theme
}
},
});
```
--------------------------------
### BEM Element Function Examples
Source: https://github.com/telegram-mini-apps/reactjs-template/blob/master/_autodocs/api-reference/utilities.md
Illustrates the usage of the ElemFn from the BEM utility for generating class names for elements within a block, including modifiers.
```typescript
const [b, e] = bem('card');
e('title') // Returns: 'card__title'
e('title', 'bold') // Returns: 'card__title card__title--bold'
e('body', { expanded: true }) // Returns: 'card__body card__body--expanded'
e('icon', ['small', 'blue']) // Returns: 'card__icon card__icon--small card__icon--blue'
```
--------------------------------
### Nested DisplayData Example
Source: https://github.com/telegram-mini-apps/reactjs-template/blob/master/_autodocs/types.md
Illustrates nesting multiple DisplayData components within a parent List component to create structured sections.
```typescript
```
--------------------------------
### ErrorBoundary Component Setup
Source: https://github.com/telegram-mini-apps/reactjs-template/blob/master/_autodocs/api-reference/components.md
Demonstrates how to wrap your application or a part of it with the ErrorBoundary component to catch rendering errors. The fallback prop accepts a component to render when an error occurs.
```typescript
import { ErrorBoundary } from '@/components/ErrorBoundary';
function ErrorFallback({ error }: { error: unknown }) {
return (
);
}
export function Root() {
return (
);
}
```
--------------------------------
### Define Theme Colors with RGB Type
Source: https://github.com/telegram-mini-apps/reactjs-template/blob/master/_autodocs/types.md
Example of defining theme colors using the `RGB` type from the SDK. This ensures type safety for color values.
```typescript
import type { RGB } from '@tma.js/sdk-react';
const themeColors: Record = {
primary: '#6ab2f2',
background: '#17212b',
accent: '#5288c1',
};
```
--------------------------------
### Example Usage of MergeClassNames Utility
Source: https://github.com/telegram-mini-apps/reactjs-template/blob/master/_autodocs/types.md
Demonstrates how to use the `mergeClassNames` function and infer the resulting type with `MergeClassNames`. This is useful for dynamically constructing CSS class names in React components.
```typescript
import { mergeClassNames, type MergeClassNames } from '@/css/classnames';
const baseClasses = { root: 'flex', text: 'text-sm' };
const variantClasses = { root: 'flex-col', icon: 'icon-md' };
const merged = mergeClassNames(baseClasses, variantClasses);
type MergedType = typeof merged; // { root: string; text: string; icon: string; }
```
--------------------------------
### TON Connect Route Icon
Source: https://github.com/telegram-mini-apps/reactjs-template/blob/master/_autodocs/api-reference/routing.md
Example of embedding an SVG icon for the TON Connect route, demonstrating how to include visual elements within route definitions.
```tsx
icon: (
)
```
--------------------------------
### App Component Configuration
Source: https://github.com/telegram-mini-apps/reactjs-template/blob/master/_autodocs/api-reference/components.md
The App component handles Telegram Mini Apps SDK integration, theme detection, routing setup, and renders the main application content. It relies on hooks for launch parameters and theme signals.
```typescript
export function App(): JSX.Element
```
```typescript
import { App } from '@/components/App';
import { Root } from '@/components/Root';
export function Root() {
return (
);
}
```
--------------------------------
### Accessing Telegram Mini App State
Source: https://github.com/telegram-mini-apps/reactjs-template/blob/master/_autodocs/architecture.md
Use the `useSignal` hook with `miniApp` to get the current state of the Mini App, such as dark mode and expand status.
```typescript
useSignal(miniApp)
```
--------------------------------
### BEM Block Class Name Generation
Source: https://github.com/telegram-mini-apps/reactjs-template/blob/master/_autodocs/types.md
Provides examples of using the BEM block function to generate class names with different modifier types. Use this for applying BEM modifiers to the main block element.
```typescript
import { bem } from '@/css/bem';
const [b, e] = bem('card');
b() // 'card'
b('active') // 'card card--active'
b({ active: true, disabled: false }) // 'card card--active'
b(['active', 'large']) // 'card card--active card--large'
```
--------------------------------
### Build the Application
Source: https://github.com/telegram-mini-apps/reactjs-template/blob/master/README.md
Run this command to build the application and generate fresh static files for deployment.
```bash
npm run build
```
--------------------------------
### init
Source: https://github.com/telegram-mini-apps/reactjs-template/blob/master/_autodocs/api-reference/exports.md
Initializes the application and configures dependencies. This function is asynchronous and accepts an options object for configuration.
```APIDOC
## init
### Description
Initializes the application and configures dependencies.
### Signature
`async (options: {debug, eruda, mockForMacOS}) => Promise`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
None
### Response
#### Success Response (200)
None
#### Response Example
None
```
--------------------------------
### Application Startup Sequence
Source: https://github.com/telegram-mini-apps/reactjs-template/blob/master/_autodocs/architecture.md
Details the step-by-step process from the application's entry point (index.tsx) through initialization and rendering of the root component.
```text
1. index.tsx (entry point)
├── Imports Telegram UI styles
├── Imports mockEnv for development
├── Calls init() function
└── Renders Root component
2. init.ts
├── Sets debug mode
├── Initializes @tma.js/sdk-react
├── Loads Eruda (if on iOS/Android debug)
├── Mocks macOS environment (if needed)
└── Mounts SDK components (backButton, initData, miniApp, etc.)
3. Root component
├── Wraps with ErrorBoundary
├── Wraps with TonConnectUIProvider
└── Renders App component
4. App component
├── Gets launch parameters
├── Detects dark/light theme
├── Configures AppRoot
├── Sets up HashRouter
└── Renders matched route
```
--------------------------------
### Deploy the Application
Source: https://github.com/telegram-mini-apps/reactjs-template/blob/master/README.md
Execute this script after building to deploy the application. Ensure the build step is completed first.
```bash
npm run deploy
```
--------------------------------
### init(options)
Source: https://github.com/telegram-mini-apps/reactjs-template/blob/master/_autodocs/api-reference/init.md
Initializes the Telegram Mini Apps SDK, configuring debug mode, Eruda console, and macOS specific workarounds. It ensures all necessary components are mounted and theme/viewport variables are bound.
```APIDOC
## init(options)
### Description
Initializes the Telegram Mini Apps SDK, configuring debug mode, Eruda console, and macOS specific workarounds. It ensures all necessary components are mounted and theme/viewport variables are bound.
### Method
`init`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
* **options** (object) - Required - Configuration object for initialization
* **options.debug** (boolean) - Required - Enables debug mode for @tma.js/sdk-react. Also controls whether Eruda debugging tools are shown based on platform.
* **options.eruda** (boolean) - Required - If true and platform is iOS or Android, loads and initializes Eruda debugging console positioned at the top-right of the screen.
* **options.mockForMacOS** (boolean) - Required - If true, applies workarounds for Telegram macOS client bugs, including handling theme request responses and safe area calculations.
### Request Example
```typescript
import { init } from '@/init.ts';
import { retrieveLaunchParams } from '@tma.js/sdk-react';
const launchParams = retrieveLaunchParams();
const platform = launchParams.tgWebAppPlatform;
const debug = import.meta.env.DEV;
await init({
debug: debug,
eruda: debug && ['ios', 'android'].includes(platform),
mockForMacOS: platform === 'macos',
});
```
### Response
#### Success Response (void)
Resolves when initialization is complete.
#### Response Example
None (Promise)
### Throws
Throws any unhandled errors from SDK initialization. Errors during dependency mounting are silent (uses `ifAvailable()` checks).
```
--------------------------------
### Building for Production
Source: https://github.com/telegram-mini-apps/reactjs-template/blob/master/_autodocs/README.md
Commands for building the optimized production bundle and deploying it to GitHub Pages. `npm run build` creates the production-ready assets, and `npm run deploy` handles the deployment process.
```bash
npm run build # Build optimized bundle
npm run deploy # Deploy to GitHub Pages
```
--------------------------------
### SDK Initialization with Error Catching
Source: https://github.com/telegram-mini-apps/reactjs-template/blob/master/_autodocs/README.md
Shows how to initialize the Telegram SDK and gracefully handle potential initialization errors. If initialization fails, it renders a specific UI indicating an unsupported environment.
```typescript
try {
await init({ debug, eruda, mockForMacOS });
} catch (e) {
root.render();
}
```
--------------------------------
### Entry Point Module (index.tsx) Behavior
Source: https://github.com/telegram-mini-apps/reactjs-template/blob/master/_autodocs/architecture.md
Describes the responsibilities and behavior of the application's entry point file, including initialization and rendering logic.
```text
1. Retrieves launch parameters from Telegram
2. Determines debug mode from start param or development mode
3. Calls init() with appropriate configuration
4. Renders Root component on success
5. Falls back to EnvUnsupported on error
```
--------------------------------
### Project Structure Overview
Source: https://github.com/telegram-mini-apps/reactjs-template/blob/master/_autodocs/architecture.md
Illustrates the directory and file organization for the React template, detailing the purpose of each major folder and key files.
```tree
src/
├── index.tsx # Application entry point
├── init.ts # Initialization logic
├── mockEnv.ts # Development environment mocking
├── components/
│ ├── Root.tsx # Top-level wrapper component
│ ├── App.tsx # Main app with routing
│ ├── Page.tsx # Page layout wrapper
│ ├── ErrorBoundary.tsx # Error handling boundary
│ ├── Link/
│ ├── DisplayData/
│ ├── RGB/
│ └── EnvUnsupported.tsx # Unsupported environment fallback
├── pages/
│ ├── IndexPage/
│ ├── InitDataPage.tsx
│ ├── LaunchParamsPage.tsx
│ ├── ThemeParamsPage.tsx
│ └── TONConnectPage/
├── navigation/
│ └── routes.tsx # Route definitions
├── helpers/
│ └── publicUrl.ts # Public URL resolution
└── css/
├── bem.ts # BEM naming utility
└── classnames.ts # Classname utility functions
```
--------------------------------
### Consuming Signals with useSignal Hook
Source: https://github.com/telegram-mini-apps/reactjs-template/blob/master/_autodocs/architecture.md
Subscribes to a signal to get its current value. The component will re-render whenever the signal's value changes.
```typescript
import { useSignal } from '@tma.js/sdk-react';
// Example usage with initData signal:
const rawInitData = useSignal(initData.raw);
const parsedInitData = useSignal(initData.state);
// Example usage with themeParams signal:
const theme = useSignal(themeParams.state);
// Example usage with miniApp signal:
const isDarkMode = useSignal(miniApp.isDark);
// Example usage with viewport signal:
const viewport = useSignal(viewport.state);
// Example usage with backButton signal:
const isBackVisible = useSignal(backButton.isVisible);
```
--------------------------------
### Get Current Route Pathname
Source: https://github.com/telegram-mini-apps/reactjs-template/blob/master/_autodocs/api-reference/routing.md
Use the `useLocation` hook from `react-router-dom` to access the current route's pathname. This is useful for displaying current location information within your component.
```typescript
import { useLocation } from 'react-router-dom';
export const MyComponent = () => {
const location = useLocation();
console.log(location.pathname); // '/init-data'
return
Current: {location.pathname}
;
};
```
--------------------------------
### Programmatic Navigation with useNavigate
Source: https://github.com/telegram-mini-apps/reactjs-template/blob/master/_autodocs/api-reference/routing.md
Illustrates how to perform navigation programmatically using React Router's `useNavigate` hook, typically triggered by user actions like button clicks.
```typescript
import { useNavigate } from 'react-router-dom';
export const MyComponent = () => {
const navigate = useNavigate();
return (
);
};
```
--------------------------------
### Import Utility Functions
Source: https://github.com/telegram-mini-apps/reactjs-template/blob/master/_autodocs/api-reference/exports.md
Import utility functions for initialization, URL handling, CSS management, and routing.
```typescript
import { init } from '@/init';
import { publicUrl } from '@/helpers/publicUrl';
import { bem } from '@/css/bem';
import { classNames, mergeClassNames, isRecord } from '@/css/classnames';
import { routes } from '@/navigation/routes';
```
--------------------------------
### Accessing Telegram Launch Parameters
Source: https://github.com/telegram-mini-apps/reactjs-template/blob/master/_autodocs/architecture.md
Use the `useLaunchParams` hook from `@tma.js/sdk-react` to access platform and version information.
```typescript
useLaunchParams()
```
--------------------------------
### Creating a New Page in React
Source: https://github.com/telegram-mini-apps/reactjs-template/blob/master/_autodocs/README.md
Illustrates the process of adding a new page to the application. This involves creating a React component and then defining its route in the application's routing configuration.
```typescript
// 1. Create component in src/pages/NewPage.tsx
import { Page } from '@/components/Page';
export const NewPage = () => (
Page content
);
// 2. Add to src/navigation/routes.tsx
export const routes: Route[] = [
{ path: '/new', Component: NewPage, title: 'New Page' },
// ...
];
```
--------------------------------
### Configure Homepage in package.json
Source: https://github.com/telegram-mini-apps/reactjs-template/blob/master/README.md
Set the `homepage` field in `package.json` to your GitHub Pages URL. This is crucial for the GitHub Pages deploy tool to correctly identify the project.
```json
{
"homepage": "https://telegram-mini-apps.github.io/is-awesome"
}
```
--------------------------------
### Import Core Components
Source: https://github.com/telegram-mini-apps/reactjs-template/blob/master/_autodocs/api-reference/exports.md
Import essential components for building the structure of your Telegram Mini App.
```typescript
import { Root } from '@/components/Root';
import { App } from '@/components/App';
import { Page } from '@/components/Page';
import { ErrorBoundary } from '@/components/ErrorBoundary';
import { Link } from '@/components/Link/Link';
import { DisplayData } from '@/components/DisplayData/DisplayData';
import { RGB } from '@/components/RGB/RGB';
import { EnvUnsupported } from '@/components/EnvUnsupported';
```
--------------------------------
### Navigating Programmatically with useNavigate
Source: https://github.com/telegram-mini-apps/reactjs-template/blob/master/_autodocs/architecture.md
Employ the `useNavigate` hook for imperative navigation, useful for handling navigation logic after certain actions.
```typescript
const navigate = useNavigate();
navigate('/init-data');
```
--------------------------------
### Accessing Telegram Data with SDK React
Source: https://github.com/telegram-mini-apps/reactjs-template/blob/master/_autodocs/README.md
Demonstrates how to access launch parameters and user data using hooks from the '@tma.js/sdk-react' library. Ensure the SDK is initialized before using these hooks.
```typescript
import { useLaunchParams, useSignal, initData } from '@tma.js/sdk-react';
export const MyComponent = () => {
const launchParams = useLaunchParams();
const userData = useSignal(initData.state);
return
{userData?.user?.first_name}
;
};
```
--------------------------------
### Initialization Module (init.ts) Function Signature
Source: https://github.com/telegram-mini-apps/reactjs-template/blob/master/_autodocs/architecture.md
Details the exported `init` function from the initialization module, including its parameters and responsibilities.
```typescript
export declare function init(options?: Options): Promise;
interface Options {
debug?: boolean;
eruda?: boolean;
mockForMacOS?: boolean;
}
```
--------------------------------
### Nested Navigation with Sections and Links
Source: https://github.com/telegram-mini-apps/reactjs-template/blob/master/_autodocs/api-reference/routing.md
Shows how to structure navigation within a page using sections and internal links, organizing content and providing clear navigation paths.
```typescript
TON ConnectInit Data
```
--------------------------------
### Data Display Pattern with useMemo
Source: https://github.com/telegram-mini-apps/reactjs-template/blob/master/_autodocs/README.md
Shows a pattern for transforming raw data into a format suitable for display components using 'useMemo' for optimization. Assumes 'data' is available and a 'DisplayData' component exists.
```typescript
const rows = useMemo(() => {
if (!data) return undefined;
return Object.entries(data).map(([title, value]) => ({
title,
value,
}));
}, [data]);
return ;
```
--------------------------------
### App Component
Source: https://github.com/telegram-mini-apps/reactjs-template/blob/master/_autodocs/api-reference/components.md
The App component is responsible for initializing the application's core features, including retrieving Telegram launch parameters, determining the theme, and setting up client-side routing.
```APIDOC
## App Component
### Description
The App component initializes the application by retrieving Telegram launch parameters, detecting the theme, configuring the appearance, and setting up client-side routing using HashRouter.
### Usage
```typescript
export function App(): JSX.Element
```
### Parameters
None. This component relies on hooks to access launch parameters and theme state.
### Example Usage
```typescript
import { App } from '@/components/App';
import { Root } from '@/components/Root';
export function Root() {
return (
);
}
```
```
--------------------------------
### App Component with React Router
Source: https://github.com/telegram-mini-apps/reactjs-template/blob/master/_autodocs/api-reference/routing.md
Sets up the application's routing using React Router's HashRouter, defining routes based on the 'routes' array and a fallback route for undefined paths.
```typescript
import { routes } from '@/navigation/routes';
import { HashRouter, Routes, Route, Navigate } from 'react-router-dom';
export function App() {
return (
{routes.map((route) => (
))}
} />
);
}
```
--------------------------------
### Vite Build Configuration
Source: https://github.com/telegram-mini-apps/reactjs-template/blob/master/_autodocs/architecture.md
Configuration for the Vite build process. Specifies the base URL, plugins, build targets, minification, and public directory.
```typescript
import react from '@vitejs/plugin-react';
import tsconfigPaths from 'vite-tsconfig-paths';
import mkcert from 'vite-plugin-mkcert';
export default {
base: '/reactjs-template/', // Base URL path
plugins: [
react(), // React plugin
tsconfigPaths(), // Path aliases
mkcert() (if HTTPS=true), // SSL certificates
],
build: {
target: 'esnext', // Modern JavaScript
minify: 'terser', // Minification
},
publicDir: './public/', // Static assets
};
```
--------------------------------
### init Function Signature
Source: https://github.com/telegram-mini-apps/reactjs-template/blob/master/_autodocs/api-reference/init.md
The signature for the `init` function, specifying its options and return type.
```typescript
export async function init(options: {
debug: boolean;
eruda: boolean;
mockForMacOS: boolean;
}): Promise
```
--------------------------------
### Navigation with Link Component and useNavigate Hook
Source: https://github.com/telegram-mini-apps/reactjs-template/blob/master/_autodocs/README.md
Demonstrates two methods for navigation within a Telegram Mini App: using the custom Link component for declarative navigation and the useNavigate hook from react-router-dom for programmatic navigation. It also shows how to link to external websites.
```typescript
import { Link } from '@/components/Link/Link';
import { useNavigate } from 'react-router-dom';
// Via Link component
Go to data
// Via navigate hook
const navigate = useNavigate();
navegate('/init-data');
// External links (automatic)
External
```
--------------------------------
### Root Component
Source: https://github.com/telegram-mini-apps/reactjs-template/blob/master/_autodocs/api-reference/components.md
The Root component is the main entry point of the application. It sets up essential providers for error handling and blockchain wallet integration, wrapping the core application logic.
```APIDOC
## Root Component
### Description
The Root component sets up error handling and blockchain wallet integration for the entire application. It wraps the main App component with necessary providers.
### Usage
```typescript
export function Root(): JSX.Element
```
### Returns
A JSX element that renders the application structure with integrated providers.
### Example Usage
```typescript
import { Root } from '@/components/Root';
import ReactDOM from 'react-dom/client';
const root = ReactDOM.createRoot(document.getElementById('root')!);
root.render();
```
```
--------------------------------
### RGB Component HTML Structure
Source: https://github.com/telegram-mini-apps/reactjs-template/blob/master/_autodocs/api-reference/components.md
Illustrates the rendered HTML structure for the RGB component, including the color swatch and text.
```html
#FF5733
```
--------------------------------
### TON Connect Data Flow
Source: https://github.com/telegram-mini-apps/reactjs-template/blob/master/_autodocs/architecture.md
Illustrates how wallet integration data is managed and accessed using the @tonconnect/ui-react provider and hooks.
```text
Wallet App
↓
TonConnectUIProvider
↓
useTonWallet() hook
↓
Connected wallet data
├── account.address
├── account.chain
├── device.platform
└── etc.
```
--------------------------------
### Import Page Components
Source: https://github.com/telegram-mini-apps/reactjs-template/blob/master/_autodocs/api-reference/exports.md
Import components that represent different pages within your Telegram Mini App.
```typescript
import { IndexPage } from '@/pages/IndexPage/IndexPage';
import { InitDataPage } from '@/pages/InitDataPage';
import { LaunchParamsPage } from '@/pages/LaunchParamsPage';
import { ThemeParamsPage } from '@/pages/ThemeParamsPage';
import { TONConnectPage } from '@/pages/TONConnectPage/TONConnectPage';
```
--------------------------------
### Back Navigation with Page Component
Source: https://github.com/telegram-mini-apps/reactjs-template/blob/master/_autodocs/api-reference/routing.md
Demonstrates how the `Page` component automatically manages the display and functionality of a back button, enabling users to navigate to the previous screen.
```typescript
import { Page } from '@/components/Page';
export const MyPage = () => {
return (
{/* Content renders with back button */}
);
};
```
--------------------------------
### Styling Components with BEM and Classnames
Source: https://github.com/telegram-mini-apps/reactjs-template/blob/master/_autodocs/architecture.md
Leverage `bem()` and `classNames()` utilities for efficient and maintainable CSS class management in components.
```typescript
const [b, e] = bem('my-block');
const className = classNames(
b({ active: isActive }),
e('content'),
additionalClass
);
```
--------------------------------
### Navigating to a New Page using Link
Source: https://github.com/telegram-mini-apps/reactjs-template/blob/master/_autodocs/architecture.md
Use the `Link` component for declarative navigation between routes within the application.
```typescript
Go to data
```
--------------------------------
### Fallback Route for Undefined Paths
Source: https://github.com/telegram-mini-apps/reactjs-template/blob/master/_autodocs/api-reference/routing.md
Configures a catch-all route that redirects any undefined paths back to the home page ('/').
```typescript
} />
```
--------------------------------
### Create a New Page Component
Source: https://github.com/telegram-mini-apps/reactjs-template/blob/master/_autodocs/api-reference/routing.md
Define a new React component for your page. Ensure it's structured to be compatible with the application's page layout, typically by wrapping it in a `Page` component.
```typescript
// src/pages/NewPage.tsx
import { Page } from '@/components/Page';
import { FC } from 'react';
export const NewPage: FC = () => {
return (
New Page Content
);
};
```
--------------------------------
### Conditional Rendering with Signals
Source: https://github.com/telegram-mini-apps/reactjs-template/blob/master/_autodocs/README.md
Demonstrates how to conditionally render elements based on a signal's value, using classNames for dynamic styling. Ensure the 'useSignal' hook and 'classNames' utility are available.
```typescript
const isActive = useSignal(miniApp.isDark);
return (
Content
);
```
--------------------------------
### publicUrl(path)
Source: https://github.com/telegram-mini-apps/reactjs-template/blob/master/_autodocs/api-reference/utilities.md
Converts a relative path to a complete public URL with the configured base path. It handles base URL retrieval, path normalization, and construction of the final URL, respecting Vite's BASE_URL configuration.
```APIDOC
## publicUrl(path)
### Description
Converts a relative path to a complete public URL with the configured base path. It handles base URL retrieval, path normalization, and construction of the final URL, respecting Vite's BASE_URL configuration.
### Method
N/A (JavaScript function)
### Parameters
#### Path Parameters
- **path** (string) - Required - Relative path to convert. Leading slashes are removed.
### Returns
`string` — Complete absolute or relative URL pointing to a public asset. The result respects the Vite BASE_URL configuration.
### Example Usage
```typescript
import { publicUrl } from '@/helpers/publicUrl';
// In vite.config.ts: base: '/reactjs-template/'
// Get manifest URL
const manifestUrl = publicUrl('tonconnect-manifest.json');
// Result: 'https://localhost:5173/reactjs-template/tonconnect-manifest.json'
// Get another asset
const iconUrl = publicUrl('/icons/app-icon.png');
// Result: 'https://localhost:5173/reactjs-template/icons/app-icon.png'
// In production with absolute URL
const prodUrl = publicUrl('config.json');
// If BASE_URL is 'https://example.com/app/'
// Result: 'https://example.com/app/config.json'
```
```
--------------------------------
### Configure Base Path in vite.config.ts
Source: https://github.com/telegram-mini-apps/reactjs-template/blob/master/README.md
Set the `base` value in `vite.config.ts` to your GitHub repository name. Vite uses this for creating paths to static assets.
```typescript
export default defineConfig({
base: '/is-awesome/',
// ...
});
```
--------------------------------
### Internal Link Navigation
Source: https://github.com/telegram-mini-apps/reactjs-template/blob/master/_autodocs/api-reference/routing.md
Demonstrates how to use the custom Link component for internal navigation within the application, directing users to different pages.
```typescript
import { Link } from '@/components/Link/Link';
View Init Data
View Theme
```
--------------------------------
### Styling with BEM Utility Functions
Source: https://github.com/telegram-mini-apps/reactjs-template/blob/master/_autodocs/README.md
Shows how to use the BEM (Block, Element, Modifier) utility functions for CSS class name generation. This helps maintain a consistent and scalable styling approach.
```typescript
import { bem, classNames } from '@/css';
export const MyComponent = () => {
const [b, e] = bem('my-component');
return (
Title
Content
);
};
```
--------------------------------
### classNames
Source: https://github.com/telegram-mini-apps/reactjs-template/blob/master/_autodocs/api-reference/exports.md
Utility function for conditionally joining class names. It accepts a variable number of arguments.
```APIDOC
## classNames
### Description
Conditional classname joining.
### Signature
`(...values: any[]) => string`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
None
### Response
#### Success Response (200)
None
#### Response Example
None
```
--------------------------------
### Import Type Definitions
Source: https://github.com/telegram-mini-apps/reactjs-template/blob/master/_autodocs/api-reference/exports.md
Import TypeScript type definitions for props, rows, and utility functions to enhance type safety.
```typescript
import type { ErrorBoundaryProps } from '@/components/ErrorBoundary';
import type { DisplayDataRow, DisplayDataProps } from '@/components/DisplayData/DisplayData';
import type { RGBProps } from '@/components/RGB/RGB';
import type { Route } from '@/navigation/routes';
import type { BlockFn, ElemFn } from '@/css/bem';
import type { MergeClassNames } from '@/css/classnames';
```
--------------------------------
### Component Hierarchy
Source: https://github.com/telegram-mini-apps/reactjs-template/blob/master/_autodocs/architecture.md
Visualizes the nested structure of the main React components, showing how they wrap each other to provide functionality like error handling and routing.
```text
Root
├── ErrorBoundary (error catching)
└── TonConnectUIProvider (wallet integration)
└── App
└── AppRoot (from telegram-ui)
└── HashRouter
└── Routes
└── Page (selected route)
└── Page-specific content
```
--------------------------------
### Add Navigation Link to New Page
Source: https://github.com/telegram-mini-apps/reactjs-template/blob/master/_autodocs/api-reference/routing.md
Create a navigation link using the `Link` component from `react-router-dom` to allow users to navigate to the newly added page.
```typescript
// In IndexPage or another page
New Page
```
--------------------------------
### External Link Handling
Source: https://github.com/telegram-mini-apps/reactjs-template/blob/master/_autodocs/README.md
Illustrates two methods for handling external links: using the 'Link' component for automatic handling and the 'openLink' function for manual control. Import 'openLink' from '@tma.js/sdk-react' if using the manual method.
```typescript
// Automatic via Link component
External
// Manual via openLink
import { openLink } from '@tma.js/sdk-react';
openLink('https://example.com');
```
--------------------------------
### External Link Handling
Source: https://github.com/telegram-mini-apps/reactjs-template/blob/master/_autodocs/api-reference/routing.md
Shows how the Link component automatically handles external URLs by using Telegram's `openLink()` method for navigation.
```typescript
// This opens with Telegram's openLink()
Visit Telegram
```
--------------------------------
### DisplayData Component for Structured Data
Source: https://github.com/telegram-mini-apps/reactjs-template/blob/master/_autodocs/api-reference/components.md
Illustrates how to use the DisplayData component to render structured data in a table format. It supports various value types including strings, booleans, undefined, RGB colors, and links.
```typescript
import { DisplayData } from '@/components/DisplayData/DisplayData';
export const MyData = () => {
const rows = [
{ title: 'Name', value: 'John Doe' },
{ title: 'Active', value: true },
{ title: 'Profile Color', value: '#FF5733' }, // RGB color
{ title: 'Email', value: undefined }, // Displays as "empty"
{ title: 'Website', type: 'link', value: 'https://example.com' },
{ title: 'More Info', type: 'link', value: '/about' },
];
return (
);
};
```
--------------------------------
### Handle External Links with openLink
Source: https://github.com/telegram-mini-apps/reactjs-template/blob/master/_autodocs/api-reference/routing.md
Use the `openLink` function from `@tma.js/sdk-react` to integrate external links. This ensures links open in the system browser and respect Telegram's policies.
```typescript
import { openLink } from '@tma.js/sdk-react';
// Via Link component (automatic)
External Site
// Manual usage
const openWebsite = () => {
openLink('https://example.com');
};
```
--------------------------------
### Application Routes Definition
Source: https://github.com/telegram-mini-apps/reactjs-template/blob/master/_autodocs/api-reference/routing.md
Defines the array of route objects for the application's navigation structure. Each route specifies a path, a corresponding React component, and an optional title and icon.
```typescript
export const routes: Route[] = [
{ path: '/', Component: IndexPage },
{ path: '/init-data', Component: InitDataPage, title: 'Init Data' },
{ path: '/theme-params', Component: ThemeParamsPage, title: 'Theme Params' },
{ path: '/launch-params', Component: LaunchParamsPage, title: 'Launch Params' },
{
path: '/ton-connect',
Component: TONConnectPage,
title: 'TON Connect',
icon: , // TON logo
},
];
```
--------------------------------
### Add New Page to Routes Configuration
Source: https://github.com/telegram-mini-apps/reactjs-template/blob/master/_autodocs/api-reference/routing.md
Register the new page component in your application's route configuration. Assign a unique `path`, the `Component` itself, and a `title` for display.
```typescript
// src/navigation/routes.tsx
import { NewPage } from '@/pages/NewPage';
export const routes: Route[] = [
// ... existing routes
{
path: '/new-page',
Component: NewPage,
title: 'New Page',
},
];
```
--------------------------------
### macOS Client Workarounds
Source: https://github.com/telegram-mini-apps/reactjs-template/blob/master/_autodocs/README.md
Provides a code snippet for applying workarounds specific to the Telegram macOS client. This involves using `mockTelegramEnv` to intercept and fix issues related to theme requests and safe area calculations.
```typescript
if (platform === 'macos') {
mockTelegramEnv({
onEvent(event, next) {
// Fix theme request
// Fix safe area calculation
},
});
}
```
--------------------------------
### Link Component
Source: https://github.com/telegram-mini-apps/reactjs-template/blob/master/_autodocs/api-reference/components.md
A navigation link component that intelligently handles both internal and external links, leveraging React Router for internal navigation and Telegram's openLink for external URLs.
```APIDOC
## Link Component
### Description
A navigation link component that intelligently handles both internal and external links. It uses React Router for internal navigation and Telegram's `openLink()` for external URLs.
### Method
React Functional Component
### Endpoint
N/A (Component)
### Props
Extends React Router's `LinkProps` and includes all HTML anchor attributes.
#### Path Parameters
N/A
#### Query Parameters
N/A
#### Request Body
N/A
### Parameters
- **to** (string | object) - Required - Internal route path or location object.
- **className** (string) - Optional - CSS classes to apply (merged with 'link' base class).
- **onClick** (function) - Optional - Click handler.
- **...rest** (any) - Optional - All other React Router Link props.
### Request Example
```typescript
import { Link } from '@/components/Link/Link';
export const Navigation = () => {
return (
);
};
```
### Response
React Router Link element with enhanced click handling.
#### Success Response (200)
N/A (Component Render)
#### Response Example
N/A (Component Render)
```
--------------------------------
### Displaying Data with DisplayData Component
Source: https://github.com/telegram-mini-apps/reactjs-template/blob/master/_autodocs/architecture.md
Utilize the `DisplayData` component to present structured information with headers and rows of key-value pairs.
```typescript
```
--------------------------------
### Link Component Usage for Navigation
Source: https://github.com/telegram-mini-apps/reactjs-template/blob/master/_autodocs/api-reference/components.md
Shows how to use the Link component for both internal routing within the app and external links. It automatically handles opening external URLs using Telegram's openLink() method.
```typescript
import { Link } from '@/components/Link/Link';
export const Navigation = () => {
return (
);
};
```
--------------------------------
### TypeScript Configuration
Source: https://github.com/telegram-mini-apps/reactjs-template/blob/master/_autodocs/architecture.md
Configuration for the TypeScript compiler. Enables strict mode, configures JSX compilation, module resolution, and path aliases.
```typescript
{
compilerOptions: {
strict: true, // Strict mode
jsx: 'react-jsx', // JSX compilation
moduleResolution: 'bundler', // Module resolution
paths: {
'@/*': './src/*' // Path aliases
},
},
}
```