Framework Integration
Embed in React
Show a Databrain dashboard or metric in a React app.
Before you start
- Your backend returns a guest token at
/api/databrain-token. Create a guest token - You have a dashboard id. Find the dashboard id
Steps
- Install the plugin.
npm install @databrainhq/plugin- Import it once in your entry file, for example
src/main.tsx.
import '@databrainhq/plugin/web';- Add a component that gets the token and renders
<dbn-dashboard>.
import { useEffect, useRef, useState } from 'react';
type DashboardElement = HTMLElement & {
options?: Record<string, unknown>;
handleServerEvent?: (...args: unknown[]) => unknown;
};
export function Dashboard({ dashboardId }: { dashboardId: string }) {
const [token, setToken] = useState<string>();
const ref = useRef<DashboardElement>(null);
useEffect(() => {
fetch('/api/databrain-token')
.then((res) => res.json())
.then((data) => setToken(data.token));
}, []);
useEffect(() => {
const el = ref.current;
if (!el) return;
el.options = { disableMetricCreation: true, hideDashboardName: true };
el.handleServerEvent = (event) => console.log(event);
}, [token, dashboardId]);
if (!token) return null;
return (
<dbn-dashboard
key={dashboardId}
ref={ref}
token={token}
dashboard-id={dashboardId}
enable-download-csv="true"
/>
);
}You see the dashboard in your app.
Show one metric
<dbn-metric key={metricId} token={token} metric-id={metricId} />How the props work
- Strings and booleans go in JSX as kebab-case attributes. Write booleans as
"true". - Objects and functions go on the element in an effect, as JS properties. This works on React 18 and 19.
- Assign an inline arrow function. Do not pass functions or objects as JSX props.
key={dashboardId}remounts the element when the dashboard changes.
If something goes wrong
-
TypeScript says
dbn-dashboarddoes not exist onJSX.IntrinsicElements. Add this file, for examplesrc/databrain.d.ts:import 'react'; declare module 'react' { namespace JSX { interface IntrinsicElements { 'dbn-dashboard': { [attr: string]: unknown }; 'dbn-metric': { [attr: string]: unknown }; } } } -
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. -
handleServerEventnever runs. Assign an inline arrow function. The element drops a named function.