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

token
string
required
Guest token for authentication. Must be generated from your backend using the Databrain API.
dashboard-id
string
required
Unique identifier for the dashboard to display.

Display & Layout Options

is-hide-table-preview
boolean
default:"false"
Hides the table preview in full screen view.
is-hide-chart-settings
boolean
default:"false"
Hides chart settings in full screen view.
disable-fullscreen
boolean
default:"false"
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
enable-download-csv
boolean
default:"false"
Enables CSV download option in metric card actions.
enable-email-csv
boolean
default:"false"
Enables email CSV option in metric card actions.
disable-download-png
boolean
default:"false"
Disables PNG download option in full screen mode.
enable-download-all-metrics
boolean
default:"false"
Enables download option for all metrics at once.

Advanced Configuration

The options prop accepts a JSON object with the following properties:
{
  "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
boolean
default:"false"
Prevents downloading data when no filters are applied.
disableDownloadUnderlyingDataNoFilters
boolean
default:"false"
Prevents downloading underlying data when no filters are applied.
isShowNoDataFoundScreen
boolean
default:"false"
Shows a custom screen when no data is available.
disableMetricCreation
boolean
default:"false"
Disables the ability to create new metrics.
disableMetricUpdation
boolean
default:"false"
Disables the ability to update existing metrics.
showDashboardActions
boolean
default:"true"
Controls visibility of dashboard actions like create metric, customize layout.
shouldFitFullScreen
boolean
default:"false"
Makes full screen modal take up space equivalent to the dashboard component.
chartColors
array
Array of color strings for chart styling. Defaults to Recharts default colors.
Configure global filters for the dashboard:
{
  "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"
  }
}
theme
object
Custom theme configuration for component styling.
theme-name
string
Name of a predefined theme from app settings UI theming.

Internationalization

language
string
default:"en"
Language code for component localization (e.g., “fr”, “es”, “de”).
translation-dictionary
object
Custom translation dictionary for component text.
calendar-type
string
default:"default"
Calendar system to use. Options: default | ind

Event Handling

handle-server-event
string
Name of a global function to handle server events. Define the function in the global scope.
// Define globally accessible function
window.myServerEventHandler = (event) => {
  console.log('Server event:', event);
  // Handle the event
};

Custom Messages

custom-messages
object
Custom messages for various component states.

Metric Component (dbn-metric)

The metric component displays a single metric with customizable appearance and interactions.

Required Properties

token
string
required
Guest token for authentication.
metric-id
string
required
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.
variant
string
default:"card"
Display variant. Options: card | fullscreen
chart-renderer-type
string
default:"svg"
Chart rendering method. Options: svg | canvas

Behavior Options

enable-download-csv
boolean
default:"false"
Enables CSV download in metric card actions.
enable-email-csv
boolean
default:"false"
Enables email CSV option in metric card actions.
disable-download-png
boolean
default:"false"
Disables PNG download in full screen mode.
disable-fullscreen
boolean
default:"false"
Disables the full screen button.
is-hide-table-preview
boolean
default:"false"
Hides table preview in full screen view.
is-hide-chart-settings
boolean
default:"false"
Hides chart settings in full screen view.
disable-underlying-data
boolean
default:"false"
Disables access to underlying data.
disable-metric-card-border
boolean
default:"false"
Removes border from metric card.
hide-metric-card-shadow
boolean
default:"false"
Removes shadow from metric card.
is-disable-card-title
boolean
default:"false"
Hides the metric card title.

Filter Configuration

enable-multi-metric-filters
boolean
default:"false"
Allows multiple metric filters.
metric-filter-position
string
default:"inside"
Position of metric filters. Options: inside | outside
metric-filter-options
object
Configuration for metric-specific filters.

Chart Appearance

chart-appearance
object
Detailed chart styling configuration.
appearance-options
object
Interactive appearance options for the metric.

Event Callbacks

on-minimize
string
Name of global function to call when metric is minimized.
window.handleMetricMinimize = (metricId) => {
  console.log('Metric minimized:', metricId);
};

Common Properties

These properties are available for both dashboard and metric components:

Styling & Customization

style
string
Inline CSS styles for the component.
class-name
string
CSS class name for custom styling.
chart-colors
array
Array of colors for chart elements.
["#FF6B6B", "#4ECDC4", "#45B7D1", "#96CEB4", "#FECA57"]

No Data Handling

no-data-img
string
SVG code as string to display when no data is available.
no-data-found-svg
string
SVG code as string to display when no data is found in dashboard.

Date Picker Configuration

hide-date-picker-options
array
Array of date picker option labels to hide.
["this month", "yesterday", "last week"]

Usage Examples

<dbn-dashboard 
  token="your-guest-token"
  dashboard-id="your-dashboard-id"
  enable-download-csv
  enable-email-csv
/>

Frequently Asked Questions

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" />
    )}
  </>
);
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;
}
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;
};
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"
      }
    ]
  }
};
Common Causes & Solutions:
  1. 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;
  }
};
  1. 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;
  }
};
  1. 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;
    }
  }
}
  1. Network/CORS Issues:
// Check browser console for CORS errors
// Ensure your backend allows requests from your domain
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' });
  }
});
Enable Canvas Rendering:
<dbn-metric 
  chart-renderer-type="canvas"
  token={token}
  metric-id="large-dataset-metric"
/>
Disable Heavy Features:
<dbn-dashboard 
  options={JSON.stringify({
    disableMainLoader: true,
    disableMetricLoader: true,
    shouldFitFullScreen: true,
    disableUnderlyingData: true
  })}
/>
Lazy Loading Implementation:
const LazyDashboard = ({ dashboardId }) => {
  const [isVisible, setIsVisible] = useState(false);
  const ref = useRef();
  
  useEffect(() => {
    const observer = new IntersectionObserver(
      ([entry]) => {
        if (entry.isIntersecting) {
          setIsVisible(true);
          observer.disconnect();
        }
      },
      { threshold: 0.1 }
    );
    
    if (ref.current) observer.observe(ref.current);
    return () => observer.disconnect();
  }, []);
  
  return (
    <div ref={ref}>
      {isVisible ? (
        <dbn-dashboard 
          token={token}
          dashboard-id={dashboardId}
        />
      ) : (
        <div>Loading dashboard...</div>
      )}
    </div>
  );
};
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)}
/>
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>
Advanced Tooltip Customization:
const tooltipConfig = {
  chartTooltip: {
    labelStyle: {
      size: 16,
      family: "Arial, sans-serif",
      weight: 600,
      color: "#2c3e50"
    },
    valueStyle: {
      size: 14,
      family: "Arial, sans-serif", 
      weight: 400,
      color: "#34495e"
    }
  }
};
Legend Positioning:
const legendConfig = {
  chartLegend: {
    show: true,
    fixedPosition: "bottom-center", // or use enableVariablePosition
    enableVariablePosition: false,
    legendAppearance: "horizontal",
    truncateLegend: 30,
    legendShape: "roundRect",
    fontSize: 12,
    fontWeight: 500,
    fontFamily: "Inter, sans-serif",
    color: "#2c3e50",
    disableLegendScrolling: false
  }
};
Complete Chart Appearance:
<dbn-metric 
  chart-appearance={JSON.stringify({
    ...tooltipConfig,
    ...legendConfig,
    chartLabel: {
      position: "top",
      radialChartposition: "outside"
    },
    chartMargin: {
      marginTop: 20,
      marginLeft: 20,
      marginRight: 20,
      marginBottom: 40
    },
    verticalAxis: {
      hideAxisLines: false,
      hideSplitLines: true,
      hideAxisLabels: false,
      axisName: "Revenue ($)",
      fontSize: 12,
      fontFamily: "Inter"
    },
    horizontalAxis: {
      hideAxisLines: false,
      hideSplitLines: true,
      hideAxisLabels: false,
      axisName: "Time Period",
      fontSize: 12,
      fontFamily: "Inter"
    }
  })}
/>

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
  • ✅ Enable canvas rendering for large datasets
  • ✅ Disable unnecessary features (loaders, underlying data)
  • ✅ Implement lazy loading for multiple components
  • ✅ Use shouldFitFullScreen for better performance

Need More Help?

Check our comprehensive troubleshooting guide for additional solutions