Skip to Content

Framework Integration

Embed with JavaScript

Show a Databrain dashboard or metric on a page with no framework.

The page uses a bundler, such as Vite, to load the npm package.

Before you start

Steps

  1. Install the plugin.
npm install @databrainhq/plugin
  1. Add a container to your HTML page.
<div id="analytics"></div>
<script type="module" src="/src/main.js"></script>
  1. In src/main.js, import the plugin, get the token and add the element.
import '@databrainhq/plugin/web';

async function showDashboard(dashboardId) {
  const res = await fetch('/api/databrain-token');
  const { token } = await res.json();

  const el = document.createElement('dbn-dashboard');
  el.setAttribute('token', token);
  el.setAttribute('dashboard-id', dashboardId);
  el.setAttribute('enable-download-csv', 'true');
  el.options = { disableMetricCreation: true, hideDashboardName: true };
  el.handleServerEvent = (event) => console.log(event);

  document.getElementById('analytics').replaceChildren(el);
}

showDashboard('your-dashboard-id');

You see the dashboard in the container.

To show a different dashboard, call showDashboard again. replaceChildren removes the old element and adds a new one.

Without a bundler

Load React, React DOM and the plugin’s UMD build with script tags. The UMD build needs React and ReactDOM on window.

<script src="https://unpkg.com/react@18/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js"></script>
<script src="https://unpkg.com/@databrainhq/plugin/dist/webcomponents.umd.js"></script>

<dbn-dashboard id="analytics" style="display:block;height:800px"></dbn-dashboard>
<script>
  fetch('/api/databrain-token')
    .then((r) => r.json())
    .then(({ token }) => {
      const el = document.getElementById('analytics');
      el.setAttribute('dashboard-id', 'your-dashboard-id');
      el.setAttribute('token', token);
    });
</script>

Without React on window, the element is never defined and the page stays blank.

Show one metric

const metric = document.createElement('dbn-metric');
metric.setAttribute('token', token);
metric.setAttribute('metric-id', 'your-metric-id');
document.getElementById('analytics').replaceChildren(metric);

Find the metric id

Write the element in HTML

If your server renders the page, it can write the element with the token.

<dbn-dashboard
  token="GUEST_TOKEN_FROM_YOUR_SERVER"
  dashboard-id="your-dashboard-id"
  enable-download-csv="true"
  options='{"disableMetricCreation":true}'
></dbn-dashboard>

In HTML, attributes are kebab case, booleans are "true" and objects are JSON strings. Functions can only be set from JavaScript.

If something goes wrong

  • The embed shows the first dashboard of the data app, not yours. Write the attribute as dashboard-id, in kebab case. Use the id, not the dashboard name.
  • handleServerEvent never runs. Assign an inline arrow function. The element drops a named function.