Skip to main content

Overview

The Dashgram React SDK provides first-class React integration for Telegram Mini Apps. It includes React hooks, context providers, and React-specific features for seamless analytics integration.
This SDK is specifically designed for Telegram Mini Apps built with React. It requires your application to be running inside Telegram’s WebApp environment.

Installation

npm install @dashgram/react
# or
yarn add @dashgram/react
# or
pnpm add @dashgram/react

Getting Started

1. Wrap Your App with DashgramProvider

Wrap your app with DashgramProvider at the root level:
import { DashgramProvider } from "@dashgram/react"

function App() {
  return (
    <DashgramProvider projectId="your-project-id" trackLevel={3}>
      <YourApp />
    </DashgramProvider>
  )
}

2. Track Custom Events (optional)

If you want to send custom events to Dashgram, use the useTrackEvent hook. Simply call it with an event name and optional properties whenever the action happens.
import { useTrackEvent } from "@dashgram/react"

function PurchaseButton() {
  const track = useTrackEvent()

  const handleClick = () => {
    track("purchase_initiated", {
      product_id: "premium-plan",
      price: 100,
      currency: "TON"
    })
  }

  return <button onClick={handleClick}>Purchase</button>
}

Complete Example

import React from "react"
import { DashgramProvider, useTrackEvent } from "@dashgram/react"

function App() {
  return (
    <DashgramProvider projectId="your-project-id" trackLevel={3} debug={true}>
      <MainContent />
    </DashgramProvider>
  )
}

function MainContent() {
  const track = useTrackEvent()

  const handlePurchase = () => {
    track("purchase_completed", {
      product_id: "premium-plan",
      price: 100
    })
  }

  return (
    <div>
      <h1>My Mini App</h1>
      <button onClick={handlePurchase}>Purchase Premium</button>
    </div>
  )
}

export default App

Track Levels

The React SDK supports the same three tracking levels as the JavaScript SDK:
Minimal tracking. Only captures basic app lifecycle events:
  • app_open - When the Mini App is opened
  • app_close - When the Mini App is closed
Use when: You only need basic usage metrics.
Comprehensive tracking. Level 1 + 2 + performance metrics + all Telegram events:
  • Scroll depth tracking
  • Element visibility
  • Web Vitals (LCP, FID, CLS)
  • Network status
  • All Telegram WebApp events
  • Performance monitoring
Use when: You need detailed performance monitoring and all Telegram events.

TypeScript Support

The SDK includes full TypeScript definitions:
import {
  DashgramProvider,
  useTrackEvent,
  type DashgramConfig,
  type EventProperties,
  type TrackLevel
} from "@dashgram/react"

const config: DashgramConfig = {
  projectId: "your-project-id",
  trackLevel: 2 as TrackLevel
}

function App() {
  return (
    <DashgramProvider {...config}>
      <YourApp />
    </DashgramProvider>
  )
}

API Reference

<DashgramProvider>

Provider component that initializes the SDK and makes it available to all child components. Props:
PropTypeRequiredDefaultDescription
projectIdstringYesYour project ID from Dashgram dashboard
trackLevel1 | 2 | 3No2Event collection level
debugbooleanNofalseEnable debug logging
disabledbooleanNofalseDisable all tracking
batchSizenumberNo10Number of events to batch before sending
flushIntervalnumberNo5000Milliseconds between automatic flushes
apiUrlstringNohttps://api.dashgram.io/v1Custom API endpoint
onErrorfunctionNoCallback for handling errors
childrenReactNodeYesYour app components
Example:
<DashgramProvider
  projectId="your-project-id"
  trackLevel={2}
  debug={false}
  batchSize={20}
  flushInterval={10000}
  onError={error => console.error("Dashgram error:", error)}
>
  <YourApp />
</DashgramProvider>

useDashgram()

Hook to access the SDK instance directly. Returns the full SDK context. Returns:
{
  track: (event: string, properties?: EventProperties) => void
  isInitialized: boolean
  flush: () => Promise<void>
  setTrackLevel: (level: TrackLevel) => void
  getTrackLevel: () => TrackLevel | undefined
  shutdown: () => void
}
Example:
import { useDashgram } from "@dashgram/react"

function MyComponent() {
  const { track, isInitialized, flush, setTrackLevel } = useDashgram()

  const handleAction = async () => {
    track("action_completed", { action: "purchase" })

    // Flush events immediately
    await flush()
  }

  if (!isInitialized) {
    return <div>Loading...</div>
  }

  return <button onClick={handleAction}>Do Action</button>
}

useTrackEvent()

Hook that returns a function to track custom events. This is the recommended way to track events in React components. Returns: (event: string, properties?: EventProperties) => void Example:
import { useTrackEvent } from "@dashgram/react"

function Button() {
  const track = useTrackEvent()

  const handleClick = () => {
    track("button_clicked", {
      button_name: "purchase",
      product_id: "premium-plan"
    })
  }

  return <button onClick={handleClick}>Click me</button>
}

usePageView(pageName, properties?)

Hook to track page views for SPA routing. Automatically prevents duplicate tracking for the same page. Parameters:
  • pageName (string) - Page identifier
  • properties (object, optional) - Additional properties
Example:
import { usePageView } from "@dashgram/react"

function HomePage() {
  usePageView("home_page", { section: "landing" })

  return <div>Home</div>
}
With React Router:
import { useLocation } from "react-router-dom"
import { usePageView } from "@dashgram/react"

function App() {
  const location = useLocation()
  usePageView(location.pathname, { search: location.search })

  return <Routes>...</Routes>
}

useScreenTracking()

Hook to automatically track screen views when using React Router. Requires react-router-dom to be installed. Example:
import { useScreenTracking } from "@dashgram/react"

function App() {
  useScreenTracking()

  return (
    <Router>
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/about" element={<About />} />
      </Routes>
    </Router>
  )
}
This hook requires react-router-dom to be installed. If not available, it will log a warning in development mode.

useTrackMount(event, properties?)

Hook to track when a component mounts. Example:
import { useTrackMount } from "@dashgram/react"

function Dashboard() {
  useTrackMount("dashboard_viewed", { user_type: "premium" })

  return <div>Dashboard</div>
}

useTrackUnmount(event, properties?)

Hook to track when a component unmounts. Example:
import { useTrackUnmount } from "@dashgram/react"

function Modal() {
  useTrackUnmount("modal_closed", { modal_type: "settings" })

  return <div>Modal content</div>
}

useAutoTrack(componentName, properties?)

Hook to automatically track component lifecycle events. Tracks ${componentName}_mounted on mount and ${componentName}_unmounted on unmount. Example:
import { useAutoTrack } from "@dashgram/react"

function MyComponent() {
  useAutoTrack("my_component", { section: "main" })

  return <div>Content</div>
}
This will automatically track:
  • my_component_mounted when the component mounts
  • my_component_unmounted when the component unmounts

useTrackClick(event, properties?)

Hook that returns a click handler function that tracks the event. Example:
import { useTrackClick } from "@dashgram/react"

function Button() {
  const handleClick = useTrackClick("button_clicked", { button: "submit" })

  return <button onClick={handleClick}>Submit</button>
}

useTrackSubmit(event, properties?)

Hook that returns a form submit handler function that tracks the event. Example:
import { useTrackSubmit } from "@dashgram/react"

function Form() {
  const handleSubmit = useTrackSubmit("form_submitted", { form: "login" })

  return (
    <form onSubmit={handleSubmit}>
      <input type="text" />
      <button type="submit">Submit</button>
    </form>
  )
}

Best Practices

1. Provider Placement

Place DashgramProvider at the root of your app, but inside your router if you’re using one:
// Good
function App() {
  return (
    <Router>
      <DashgramProvider projectId="your-project-id">
        <Routes>...</Routes>
      </DashgramProvider>
    </Router>
  )
}

2. Use Hooks Appropriately

  • Use useTrackEvent() for most custom events
  • Use usePageView() for page/screen tracking
  • Use useAutoTrack() for component lifecycle tracking
  • Use useDashgram() when you need full SDK access

3. Avoid Tracking in Render

Don’t track events directly in render. Use hooks or event handlers:
// ❌ Bad: Tracks on every render
function Component() {
  const track = useTrackEvent()
  track("viewed") // Don't do this!
  return <div>Content</div>
}

// ✅ Good: Track in useEffect or event handler
function Component() {
  const track = useTrackEvent()

  useEffect(() => {
    track("viewed")
  }, [track])

  return <div>Content</div>
}

4. Memoize Event Handlers

For frequently re-rendered components, memoize event handlers:
import { useCallback } from "react"
import { useTrackEvent } from "@dashgram/react"

function Button() {
  const track = useTrackEvent()

  const handleClick = useCallback(() => {
    track("button_clicked", { button: "submit" })
  }, [track])

  return <button onClick={handleClick}>Submit</button>
}

Troubleshooting

Provider Not Found Error

If you see “useDashgram must be used within DashgramProvider”:
  1. Ensure DashgramProvider wraps your component tree
  2. Check that you’re importing from @dashgram/react
  3. Verify the component using the hook is a child of the provider

Events Not Sending

  1. Check initialization: Ensure DashgramProvider has a valid projectId
  2. Verify Telegram environment: SDK only works inside Telegram WebApp
  3. Enable debug mode: Set debug={true} on DashgramProvider
  4. Check console: Look for Dashgram debug logs

Next Steps