Interactive Demo Try out the components with different options in DataBrain’s playground
This reference guide provides detailed documentation for all available options and properties for Databrain’s web components: dbn-dashboard
and dbn-metric
.
Dashboard Component (dbn-dashboard
)
The dashboard component displays a complete dashboard with multiple metrics and interactive features.
Required Properties
Guest token for authentication. Must be generated from your backend using the Databrain API.
Unique identifier for the dashboard to display.
Display & Layout Options
Hides the table preview in full screen view.
Hides chart settings in full screen view.
Disables the full screen option for the dashboard.
options-icon
string
default: "kebab-menu-vertical"
Controls which options icon to display. Options: kebab-menu-vertical
| download
Download & Export Options
Enables CSV download option in metric card actions.
Enables email CSV option in metric card actions.
Disables PNG download option in full screen mode.
enable-download-all-metrics
Enables download option for all metrics at once.
Advanced Configuration
The options
prop accepts a JSON object with the following properties: Basic Options
Chart Customization
{
"disableDownloadDataNoFilters" : false ,
"disableDownloadUnderlyingDataNoFilters" : false ,
"isShowNoDataFoundScreen" : false ,
"disableMetricCreation" : false ,
"disableMetricUpdation" : false ,
"disableMetricCardBorder" : false ,
"disableMetricDeletion" : false ,
"disableLayoutCustomization" : false ,
"disableSaveLayout" : false ,
"disableScheduleEmailReports" : false ,
"disableManageMetrics" : false ,
"disableMainLoader" : false ,
"disableMetricLoader" : false ,
"hideDashboardName" : false ,
"hideMetricCardShadow" : false ,
"showDashboardActions" : true ,
"disableUnderlyingData" : false ,
"shouldFitFullScreen" : false
}
disableDownloadDataNoFilters
Prevents downloading data when no filters are applied.
disableDownloadUnderlyingDataNoFilters
Prevents downloading underlying data when no filters are applied.
Shows a custom screen when no data is available.
Disables the ability to create new metrics.
Disables the ability to update existing metrics.
Controls visibility of dashboard actions like create metric, customize layout.
Makes full screen modal take up space equivalent to the dashboard component.
Array of color strings for chart styling. Defaults to Recharts default colors. [ "#FF6B6B" , "#4ECDC4" , "#45B7D1" , "#96CEB4" , "#FECA57" ]
Configure global filters for the dashboard: String Filter
Number Filter
Date Filter
{
"Filter name for a string datatype" : {
"options" : [
{ "value" : "James Smith" , "label" : "James" },
{ "value" : "Olivia Johnson" , "label" : "Olivia" },
{ "value" : "Emma Brown" , "label" : "Emma" }
],
"defaultOption" : "James Smith"
}
}
Custom theme configuration for component styling. {
"button" : {
"primaryText" : "white" ,
"primary" : "#007bff" ,
"secondaryText" : "black" ,
"secondary" : "white"
},
"checkbox" : {
"checked" : "#007bff" ,
"unChecked" : "#6c757d"
},
"switch" : {
"enabled" : "#28a745" ,
"disabled" : "#6c757d"
},
"drillBreadCrumbs" : {
"fontFamily" : "Inter" ,
"fontColor" : "black" ,
"activeColor" : "#007bff"
},
"multiSelectFilterDropdown" : {
"badgeColor" : "#007bff" ,
"badgeTextColor" : "white"
}
}
Name of a predefined theme from app settings UI theming.
Internationalization
Language code for component localization (e.g., “fr”, “es”, “de”).
Custom translation dictionary for component text. {
"total sales" : {
"en" : "total sales" ,
"fr" : "ventes totales" ,
"es" : "ventas totales" ,
"de" : "Gesamtumsatz"
}
}
Calendar system to use. Options: default
| ind
Event Handling
Name of a global function to handle server events. Define the function in the global scope. Function Definition
Component Usage
// Define globally accessible function
window . myServerEventHandler = ( event ) => {
console . log ( 'Server event:' , event );
// Handle the event
};
Custom Messages
Custom messages for various component states. {
"tokenExpiry" : "Your session has expired. Please refresh the page." ,
"tokenAbsent" : "Authentication token is missing. Please log in again."
}
Metric Component (dbn-metric
)
The metric component displays a single metric with customizable appearance and interactions.
Required Properties
Guest token for authentication.
Unique identifier for the metric to display.
Display Properties
width
string|number
default: "500"
Width of the metric component in pixels.
height
string|number
default: "300"
Height of the metric component in pixels.
Display variant. Options: card
| fullscreen
Chart rendering method. Options: svg
| canvas
Behavior Options
Enables CSV download in metric card actions.
Enables email CSV option in metric card actions.
Disables PNG download in full screen mode.
Disables the full screen button.
Hides table preview in full screen view.
Hides chart settings in full screen view.
Disables access to underlying data.
disable-metric-card-border
Removes border from metric card.
Removes shadow from metric card.
Hides the metric card title.
Filter Configuration
enable-multi-metric-filters
Allows multiple metric filters.
Position of metric filters. Options: inside
| outside
Configuration for metric-specific filters. Show Filter Configuration
{
"Filter name for a string datatype" : {
"options" : [
{ "value" : "James Smith" , "label" : "James" },
{ "value" : "Olivia Johnson" , "label" : "Olivia" }
],
"defaultOption" : "James Smith"
},
"Filter name for a number datatype" : {
"options" : [
{ "value" : 1 , "label" : "Option 1" },
{ "value" : 2 , "label" : "Option 2" }
],
"defaultOption" : 1
},
"Filter name for a date datatype" : {
"options" : [
{
"range" : "Last" ,
"time" : "Year" ,
"name" : "Last 10 Years" ,
"count" : 10 ,
"fromDate" : "2023-01-01" ,
"toDate" : "2023-12-31"
}
],
"defaultOption" : "Last 10 Years"
}
}
Chart Appearance
Detailed chart styling configuration. Show Chart Appearance Options
{
"chartTooltip" : {
"labelStyle" : {
"size" : 14 ,
"family" : "Inter" ,
"weight" : 400 ,
"color" : "#000000"
},
"valueStyle" : {
"size" : 14 ,
"family" : "Inter" ,
"weight" : 400 ,
"color" : "#000000"
}
},
"chartLabel" : {
"position" : "top" ,
"radialChartposition" : "outside"
},
"chartMargin" : {
"marginTop" : 15 ,
"marginLeft" : 15 ,
"marginRight" : 15 ,
"marginBottom" : 15
},
"chartLegend" : {
"show" : true ,
"fixedPosition" : "top-right" ,
"enableVariablePosition" : true ,
"legendAppearance" : "horizontal" ,
"truncateLegend" : 22 ,
"legendShape" : "circle" ,
"fontSize" : 14 ,
"fontWeight" : 400 ,
"fontFamily" : "Inter" ,
"color" : "#000000"
},
"verticalAxis" : {
"hideAxisLines" : false ,
"hideSplitLines" : false ,
"hideAxisLabels" : false ,
"axisName" : "Y Axis" ,
"fontSize" : 14 ,
"fontFamily" : "Inter"
},
"horizontalAxis" : {
"hideAxisLines" : false ,
"hideSplitLines" : false ,
"hideAxisLabels" : false ,
"axisName" : "X Axis" ,
"fontSize" : 14 ,
"fontFamily" : "Inter"
}
}
Interactive appearance options for the metric. {
"appearanceOptionsPosition" : "top-right" ,
"dynamicBehaviour" : {
"isEnabled" : true ,
"label" : "Dynamic"
},
"cumulativeBar" : {
"isEnabled" : true ,
"label" : "Cumulative"
},
"stackedBars" : {
"isEnabled" : true ,
"label" : "Stacked"
}
}
Event Callbacks
Name of global function to call when metric is minimized. Function Definition
Component Usage
window . handleMetricMinimize = ( metricId ) => {
console . log ( 'Metric minimized:' , metricId );
};
Common Properties
These properties are available for both dashboard and metric components:
Styling & Customization
Inline CSS styles for the component.
CSS class name for custom styling.
Array of colors for chart elements. [ "#FF6B6B" , "#4ECDC4" , "#45B7D1" , "#96CEB4" , "#FECA57" ]
No Data Handling
SVG code as string to display when no data is available.
SVG code as string to display when no data is found in dashboard.
Date Picker Configuration
Array of date picker option labels to hide. [ "this month" , "yesterday" , "last week" ]
Usage Examples
Basic Dashboard Customized Dashboard Basic Metric Advanced Metric < dbn-dashboard
token = "your-guest-token"
dashboard-id = "your-dashboard-id"
enable-download-csv
enable-email-csv
/>
Frequently Asked Questions
How do I pass props dynamically or re-render components on prop changes?
Web components don’t automatically re-render when properties change. Here are several approaches: Method 1: Force Re-render with Key const [ componentKey , setComponentKey ] = useState ( 0 );
const [ token , setToken ] = useState ( initialToken );
// When updating props
const updateProps = ( newToken ) => {
setToken ( newToken );
setComponentKey ( prev => prev + 1 ); // Force re-render
};
return (
< dbn-dashboard
key = { componentKey }
token = { token }
dashboard-id = "your-dashboard-id"
/>
);
Method 2: Loading State Approach const [ isLoading , setIsLoading ] = useState ( false );
const [ token , setToken ] = useState ( initialToken );
const updateToken = async ( newToken ) => {
setIsLoading ( true );
// Brief delay to ensure component unmounts
await new Promise ( resolve => setTimeout ( resolve , 100 ));
setToken ( newToken );
setIsLoading ( false );
};
return (
<>
{ isLoading ? (
< div > Loading... </ div >
) : (
< dbn-dashboard token = { token } dashboard-id = "your-dashboard-id" />
) }
</>
);
Why are my custom colors not applying to charts?
This usually happens due to incorrect format or timing. Here are common solutions: Ensure Proper Format: // ✅ Correct - Array of hex colors
const chartColors = [ "#FF6B6B" , "#4ECDC4" , "#45B7D1" , "#96CEB4" ];
// ❌ Incorrect - Invalid color format
const chartColors = [ "red" , "blue" ]; // Use hex codes instead
Use JSON.stringify for Complex Objects: <!-- ✅ Correct -->
< dbn-dashboard
chart-colors = {JSON.stringify([ "#FF6B6B", "#4ECDC4"])}
options = {JSON.stringify({
chartColors: [ "#FF6B6B", "#4ECDC4"]
})}
/>
<!-- ❌ Incorrect -->
< dbn-dashboard chart-colors = {[ "#FF6B6B", "#4ECDC4"]} />
Check CSS Specificity: /* Your custom colors might be overridden */
.your-dashboard-container {
--chart-color-1 : #FF6B6B !important ;
--chart-color-2 : #4ECDC4 !important ;
}
How do I handle authentication token expiry?
Set Up Custom Messages: < dbn-dashboard
token = {token}
dashboard-id = "your-dashboard-id"
custom-messages = {JSON.stringify({
tokenExpiry: "Your session has expired. Redirecting to login... ",
tokenAbsent: "Please log in to view this dashboard. "
})}
handle-server-event = "handleAuthError"
/>
Handle Server Events: // Define globally accessible function
window . handleAuthError = ( event ) => {
if ( event . type === 'TOKEN_EXPIRED' ) {
// Redirect to login or refresh token
window . location . href = '/login' ;
}
};
Automatic Token Refresh: const useTokenRefresh = () => {
const [ token , setToken ] = useState ( null );
useEffect (() => {
const refreshToken = async () => {
try {
const response = await fetch ( '/api/refresh-token' );
const { token : newToken } = await response . json ();
setToken ( newToken );
} catch ( error ) {
console . error ( 'Token refresh failed:' , error );
}
};
// Refresh token every 50 minutes (assuming 1-hour expiry)
const interval = setInterval ( refreshToken , 50 * 60 * 1000 );
refreshToken (); // Initial call
return () => clearInterval ( interval );
}, []);
return token ;
};
How do I customize the appearance of filters and date pickers?
Hide Specific Date Picker Options: < dbn-dashboard
hide-date-picker-options = {JSON.stringify([
"yesterday",
"last week ",
"this month "
])}
/>
Custom Filter Styling: < dbn-dashboard
theme = {JSON.stringify({
multiSelectFilterDropdown: {
badgeColor: "#007bff",
badgeTextColor: "white"
}
})}
admin-theme-options = {JSON.stringify({
dashboard: {
selectBoxSize: "large",
selectBoxVariant: "floating",
selectBoxBorderRadius: "8px",
selectBoxTextColor: "#333"
}
})}
/>
Global Filter Configuration: const globalFilters = {
"Region" : {
options: [
{ value: "north" , label: "North America" },
{ value: "europe" , label: "Europe" },
{ value: "asia" , label: "Asia Pacific" }
],
defaultOption: "north"
},
"Date Range" : {
defaultOption: { startDate: "2024-01-01" , endDate: "2024-12-31" },
datePresetOptions: [
{
type: "last" ,
interval: 30 ,
timeGrain: "day" ,
label: "Last 30 Days"
}
]
}
};
Why is my dashboard not loading or showing blank?
Common Causes & Solutions:
Invalid Token:
// Check token validity
const validateToken = async ( token ) => {
try {
const response = await fetch ( '/api/validate-token' , {
headers: { Authorization: `Bearer ${ token } ` }
});
return response . ok ;
} catch ( error ) {
console . error ( 'Token validation failed:' , error );
return false ;
}
};
Incorrect Dashboard ID:
// Verify dashboard exists
const checkDashboard = async ( dashboardId ) => {
try {
const response = await fetch ( `/api/dashboards/ ${ dashboardId } ` );
return response . ok ;
} catch ( error ) {
console . error ( 'Dashboard check failed:' , error );
return false ;
}
};
Missing Import:
// Ensure web components are imported
import '@databrainhq/plugin/web' ;
// For TypeScript, add declarations
declare global {
namespace JSX {
interface IntrinsicElements {
'dbn-dashboard' : any ;
'dbn-metric' : any ;
}
}
}
Network/CORS Issues:
// Check browser console for CORS errors
// Ensure your backend allows requests from your domain
How do I implement multi-tenant access control?
Client-Side Implementation: const DashboardWithTenancy = ({ userId , tenantId }) => {
const [ token , setToken ] = useState ( null );
useEffect (() => {
const fetchTenantToken = async () => {
const response = await fetch ( '/api/guest-token' , {
method: 'POST' ,
headers: { 'Content-Type' : 'application/json' },
body: JSON . stringify ({
clientId: userId ,
tenantId: tenantId ,
dataAppName: 'your-app-name'
})
});
const { token } = await response . json ();
setToken ( token );
};
fetchTenantToken ();
}, [ userId , tenantId ]);
if (! token ) return < div > Loading... </ div > ;
return (
< dbn-dashboard
token = { token }
dashboard-id = "tenant-specific-dashboard"
/>
);
};
Backend Token Generation: // Node.js example
app . post ( '/api/guest-token' , async ( req , res ) => {
const { clientId , tenantId , dataAppName } = req . body ;
try {
const response = await fetch ( 'https://api.usedatabrain.com/api/v2/guest-token/create' , {
method: 'POST' ,
headers: {
'Authorization' : `Bearer ${ process . env . DATABRAIN_API_TOKEN } ` ,
'Content-Type' : 'application/json'
},
body: JSON . stringify ({
clientId: ` ${ tenantId } _ ${ clientId } ` , // Prefix with tenant
dataAppName: dataAppName
})
});
const data = await response . json ();
res . json ({ token: data . token });
} catch ( error ) {
res . status ( 500 ). json ({ error: 'Token generation failed' });
}
});
How do I optimize performance for large dashboards?
How do I handle different screen sizes and responsive design?
Responsive Width/Height: const ResponsiveMetric = () => {
const [ dimensions , setDimensions ] = useState ({ width: 500 , height: 300 });
useEffect (() => {
const handleResize = () => {
const container = document . getElementById ( 'metric-container' );
if ( container ) {
setDimensions ({
width: container . offsetWidth ,
height: Math . min ( container . offsetWidth * 0.6 , 400 )
});
}
};
window . addEventListener ( 'resize' , handleResize );
handleResize (); // Initial call
return () => window . removeEventListener ( 'resize' , handleResize );
}, []);
return (
< div id = "metric-container" >
< dbn-metric
token = { token }
metric-id = "responsive-metric"
width = { dimensions . width }
height = { dimensions . height }
/>
</ div >
);
};
CSS Media Queries: .dashboard-container {
width : 100% ;
max-width : 1200px ;
margin : 0 auto ;
}
@media ( max-width : 768px ) {
.dashboard-container {
padding : 10px ;
}
dbn-dashboard {
--metric-card-padding : 8px ;
--font-size-small : 12px ;
}
}
@media ( max-width : 480px ) {
dbn-dashboard {
--chart-height : 200px ;
--hide-chart-legend : true;
}
}
Mobile-Specific Options: const isMobile = window . innerWidth < 768 ;
const mobileOptions = {
hideMetricCardShadow: true ,
shouldFitFullScreen: true ,
chartAppearance: {
chartLegend: { show: false },
chartMargin: { marginTop: 5 , marginLeft: 5 , marginRight: 5 , marginBottom: 5 }
}
};
< dbn-dashboard
options = { JSON . stringify ( isMobile ? mobileOptions : desktopOptions ) }
/>
How do I implement custom error handling and logging?
Global Error Handler: window . databrainErrorHandler = ( error ) => {
// Log to your analytics service
analytics . track ( 'Databrain Error' , {
error: error . message ,
component: error . component ,
timestamp: new Date (). toISOString ()
});
// Show user-friendly message
if ( error . type === 'NETWORK_ERROR' ) {
showToast ( 'Connection issue. Please check your internet connection.' );
} else if ( error . type === 'AUTH_ERROR' ) {
redirectToLogin ();
} else {
showToast ( 'Something went wrong. Please try again.' );
}
};
Component-Level Error Boundaries: class DashboardErrorBoundary extends React . Component {
constructor ( props ) {
super ( props );
this . state = { hasError: false , error: null };
}
static getDerivedStateFromError ( error ) {
return { hasError: true , error };
}
componentDidCatch ( error , errorInfo ) {
console . error ( 'Dashboard Error:' , error , errorInfo );
// Log to error reporting service
}
render () {
if ( this . state . hasError ) {
return (
< div className = "error-fallback" >
< h3 > Dashboard temporarily unavailable </ h3 >
< button onClick = { () => this . setState ({ hasError: false }) } >
Try Again
</ button >
</ div >
);
}
return this . props . children ;
}
}
// Usage
< DashboardErrorBoundary >
< dbn-dashboard token = { token } dashboard-id = "dashboard-id" />
</ DashboardErrorBoundary >
How do I customize chart tooltips and legends?
Migration & Updates
When updating from older versions, note that some property names may have changed. Always refer to this reference for the latest property names and structures.
For dynamic property updates, web components don’t automatically re-render. Consider using a loading state and temporarily hiding/showing the component when updating properties.
Troubleshooting Quick Reference
✅ Check if @databrainhq/plugin/web
is imported
✅ Verify token is valid and not expired
✅ Confirm dashboard-id/metric-id exists
✅ Check browser console for errors
✅ Ensure CORS is properly configured
✅ Use JSON.stringify()
for object props
✅ Check CSS specificity conflicts
✅ Verify color format (use hex codes)
✅ Test with !important
to identify overrides
Need More Help? Check our comprehensive troubleshooting guide for additional solutions