> ## Documentation Index
> Fetch the complete documentation index at: https://docs.usedatabrain.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Reactjs

## @databrainhq/plugin

> Databrain app UI web component plugin.

> [card] [npm: @databrainhq/plugin](https://www.npmjs.com/package/@databrainhq/plugin)
>
> v0.15.135-uat

> [card] [Code Style: StandardJS](https://standardjs.com/)
>
> Enforced using StandardJS styleguide.

To see the full list of options please check the [options list](https://docs.usedatabrain.com/developer-docs/helpers/options.md).

## Install

```bash theme={"dark"}
npm install @databrainhq/plugin
```

## Github Repo Link

> [card] [React Demo Repository](https://github.com/databrainhq/dbn-demos-updated/tree/main/dbn-demo-react)
>
> View the complete React integration example on GitHub

## Usage

**Quick usage:**

```tsx showLineNumbers title="App.tsx" theme={"dark"}
// React + Databrain plugin example

import React, { useState, useEffect } from 'react';
import '@databrainhq/plugin/web';
import './App.css';

declare global {
  namespace JSX {
    interface IntrinsicElements {
      'dbn-dashboard': any;
      'dbn-metric': any;
    }
  }
}

function App() {
  const [token, setToken] = useState<string | null>(null);
  const dashboardId = 'your-dashboard-id'; // Replace with your actual dashboard ID

  useEffect(() => {
    const fetchToken = async () => {
      try {
        const response = await fetch('/fetch-guest-token');
        if (!response.ok) {
          throw new Error('Failed to fetch token');
        }
        const data = await response.json();
        setToken(data.token); // Assuming the API returns the token in a 'token' field
      } catch (error) {
        console.error('Error fetching token:', error);
      }
    };

    fetchToken();
  }, []);

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

  return (
    <dbn-dashboard token={token} dashboard-id={dashboardId} />
  );
}

export default App;
```

For embedding a Metric Card you can use the `dbn-metric` webcomponent:

```html theme={"dark"}
<dbn-metric token="guest-token" metric-id="metricId" />
```

### Token

The [`token`](https://docs.usedatabrain.com/developer-docs/helpers/token-body) should be a guest token, fetched from your backend based on the current user's login information. You can follow the document below for guest token generation.

Token

Here is an example with sample token and dashboardId that you can use in your frontend app to get started without a backend.

```html theme={"dark"}
<dbn-dashboard token="3affda8b-7bd4-4a88-9687-105a94cfffab" dashboard-id="ex-demo" />
```

#### Breakdown:

Import the library main or index or App or layout file

```ts theme={"dark"}
import '@databrainhq/plugin/web';
```

Once the library is imported, the web-components `dbn-dashboard`, `dbn-metrics` are available to use anywhere inside your app. And you can use it anywhere in your app like:

```tsx theme={"dark"}
const Example = () => {
  return (
    <dbn-dashboard
      token="Your Guest Token"
      dashboard-id="Your Dashboard Id"
      is-hide-table-preview
      is-hide-chart-settings
      enable-download-csv
      enable-email-csv
      options-icon="kebab-menu-vertical"
      enable-multi-metric-filters
      disable-fullscreen
      theme-name="Name of the theme you want to apply from app settings ui theming"
      custom-messages={JSON.stringify({
        tokenExpiry: "Some custom message you want to show here."
      })}
      options={JSON.stringify({
        disableMetricCreation: false,
        disableMetricUpdation: false,
        disableMetricDeletion: false,
        disableLayoutCustomization: false,
        hideDashboardName: false,
        chartColors: [
          'violet',
          'indigo',
          'blue',
          'green',
          'yellow',
          'orange',
          'red',
          'pink',
          'gray',
        ],
      })}
      theme={JSON.stringify({})}
    />
  );
};
```

## Intgerating Metric

```tsx theme={"dark"}
const Example = () => {
  return (
    <dbn-metric
      token="Your Guest Token"
      metric-id="Your Metric Id"
      width="500"
      height="300"
      is-hide-chart-settings
      is-hide-table-preview
      enable-download-csv
      enable-email-csv
      enable-multi-metric-filters
      options-icon="kebab-menu-vertical"
      metric-filter-position="outside"
      chart-renderer-type="canvas"
      disable-fullscreen
      theme-name="Name of the theme you want to apply from app settings ui theming"
      custom-messages={JSON.stringify({
        tokenExpiry: "Some custom message you want to show here."
      })}
      chart-colors={JSON.stringify([
        'violet',
        'indigo',
        'blue',
        'green',
        'yellow',
        'orange',
        'red',
        'pink',
        'gray',
      ])}
      metric-filter-options={JSON.stringify({
        "Filter name for a string datatype": {
          options: ['hello', 'hi'],
          defaultOption: 'hello',
        },
        "Filter name for a number datatype": {
          options: [9, 19, 23],
          defaultOption: 19,
        },
        "Filter name for a date datatype": {
          options: [{
            range: 'Last',
            time: 'Day',
            name: 'Last 10 Years',
            count: 10,
            fromDate: '2024-01-01',
            toDate: '2024-12-31',
            minDate: '2023-01-01',
            maxDate: '2024-12-31'
          },{
            range: 'This',
            time: 'Year',
            name: 'This Year',
            count: 0,
            minDate: '2024-01-01',
            maxDate: '2024-12-31'
          }],
          defaultOption: 'Last 10 Years'
        },
      })}
      theme={JSON.stringify({})}
      appearance-options={JSON.stringify({
        appearanceOptionsPosition: 'top-left',
        cumulativeBar: {
          isEnabled: true,
          label: 'Cumulative'
        },
        stackedBars: {
          isEnabled: true,
          label: '100% stacked bars'
        },
        dynamicBehaviour: {
          isEnabled: true,
          label: 'Dynamic'
        },
      })}
    />
  );
};
```


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.