or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

annotations.mdchart-components.mdchart-container.mdg-components.mdg2-integration.mdgeometry-components.mdindex.mdmigration-guide.mdreact-hooks.mdstatistical-charts.mdtheme-system.mdutilities.md
tile.json

react-hooks.mddocs/

React Hooks

BizCharts provides React hooks for accessing chart instances, views, and managing themes within components. These hooks enable deep integration with the underlying G2 visualization engine and provide programmatic control over chart behavior.

Capabilities

useChartInstance Hook

Access the current chart instance from the chart context, allowing direct manipulation of the G2 chart object.

/**
 * Hook to access the current chart instance from context
 * @returns Chart instance from the nearest Chart component
 */
function useChartInstance(): Chart;

/**
 * Legacy alias for useChartInstance (will be removed in v5.0)
 * @deprecated Use useChartInstance instead
 */
function useRootChart(): Chart;

Usage Examples:

import React, { useEffect } from "react";
import { Chart, Line, useChartInstance } from "bizcharts";

// Custom component accessing chart instance
function ChartController() {
  const chart = useChartInstance();

  useEffect(() => {
    if (chart) {
      // Direct access to G2 chart methods
      console.log('Chart size:', chart.getSize());
      
      // Add custom interaction
      chart.interaction('brush-filter');
      
      // Listen to chart events
      chart.on('plot:click', (e) => {
        console.log('Chart clicked:', e);
      });
      
      // Custom rendering logic
      chart.render();
    }
  }, [chart]);

  return null; // This component doesn't render anything
}

// Usage within a chart
function InteractiveChart() {
  return (
    <Chart height={400} data={data} autoFit>
      <Line position="x*y" />
      <ChartController />
    </Chart>
  );
}

// Advanced chart manipulation
function AdvancedChartControl() {
  const chart = useChartInstance();

  const exportChart = () => {
    if (chart) {
      // Export chart as image
      const dataURL = chart.toDataURL();
      console.log('Chart exported:', dataURL);
    }
  };

  const updateData = (newData) => {
    if (chart) {
      // Update chart data programmatically
      chart.changeData(newData);
    }
  };

  const addAnnotation = () => {
    if (chart) {
      // Add annotation programmatically
      chart.annotation().text({
        position: ['50%', '50%'],
        content: 'Dynamic Annotation',
        style: { fontSize: 16, fill: 'red' }
      });
      chart.render();
    }
  };

  return (
    <div>
      <button onClick={exportChart}>Export Chart</button>
      <button onClick={() => updateData(newDataSet)}>Update Data</button>
      <button onClick={addAnnotation}>Add Annotation</button>
    </div>
  );
}

useView Hook

Access the current chart view from the view context, useful for multi-view charts and nested visualizations.

/**
 * Hook to access the current chart view from context
 * @returns View instance from the nearest View component
 */
function useView(): View;

Usage Examples:

import React, { useEffect } from "react";
import { Chart, View, Line, useView } from "bizcharts";

// Component accessing view instance
function ViewController() {
  const view = useView();

  useEffect(() => {
    if (view) {
      // Access view-specific methods
      console.log('View data:', view.getData());
      
      // View-level interactions
      view.interaction('element-active');
      
      // View filtering
      view.filter('category', (val) => val !== 'excluded');
      
      // View coordinate transformation
      view.coordinate('polar');
    }
  }, [view]);

  return null;
}

// Multi-view chart with view controllers
function MultiViewChart() {
  return (
    <Chart height={400} autoFit>
      <View data={leftData} region={{ start: [0, 0], end: [0.5, 1] }}>
        <Line position="x*y" />
        <ViewController />
      </View>
      <View data={rightData} region={{ start: [0.5, 0], end: [1, 1] }}>
        <Line position="x*y" color="red" />
        <ViewController />
      </View>
    </Chart>
  );
}

// View-specific data operations
function ViewDataManager() {
  const view = useView();

  const filterData = (filterValue) => {
    if (view) {
      view.filter('category', (val) => val === filterValue);
      view.render();
    }
  };

  const transformCoordinate = (type) => {
    if (view) {
      view.coordinate(type);
      view.render();
    }
  };

  return (
    <div>
      <button onClick={() => filterData('A')}>Show Category A</button>
      <button onClick={() => filterData('B')}>Show Category B</button>
      <button onClick={() => transformCoordinate('polar')}>Polar View</button>
      <button onClick={() => transformCoordinate('rect')}>Rectangle View</button>
    </div>
  );
}

useTheme Hook

Manage chart themes dynamically with state management for theme switching.

/**
 * Hook for theme management with state
 * @param defaultThemeName - Default theme name to use
 * @returns Tuple of [currentTheme, setTheme function]
 */
function useTheme(defaultThemeName?: string): [object, (themeName: string) => void];

Usage Examples:

import React from "react";
import { Chart, Line, useTheme } from "bizcharts";

// Theme switcher component
function ThemeSwitcher() {
  const [theme, setTheme] = useTheme('default');

  return (
    <div>
      <button onClick={() => setTheme('light')}>Light Theme</button>
      <button onClick={() => setTheme('dark')}>Dark Theme</button>
      <button onClick={() => setTheme('default')}>Default Theme</button>
      <p>Current theme: {theme.name || 'default'}</p>
    </div>
  );
}

// Chart with theme management
function ThemedChart() {
  const [theme, setTheme] = useTheme('light');

  return (
    <div>
      <div style={{ marginBottom: 20 }}>
        <button 
          onClick={() => setTheme('light')}
          style={{ marginRight: 10 }}
        >
          Light
        </button>
        <button 
          onClick={() => setTheme('dark')}
          style={{ marginRight: 10 }}
        >
          Dark  
        </button>
        <button onClick={() => setTheme('default')}>
          Default
        </button>
      </div>
      
      <Chart 
        height={400} 
        data={data} 
        autoFit
        theme={theme}
      >
        <Line position="month*value" />
      </Chart>
    </div>
  );
}

// Advanced theme customization
function CustomThemedChart() {
  const [theme, setTheme] = useTheme();

  const applyCustomTheme = () => {
    const customTheme = {
      name: 'custom',
      colors10: ['#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4', '#FFEAA7'],
      backgroundColor: '#2C3E50',
      subColor: '#34495E',
      semanticRed: '#E74C3C',
      semanticGreen: '#2ECC71'
    };
    setTheme(customTheme);
  };

  return (
    <div>
      <button onClick={() => setTheme('light')}>Light</button>
      <button onClick={() => setTheme('dark')}>Dark</button>
      <button onClick={applyCustomTheme}>Custom</button>
      
      <Chart height={400} data={data} autoFit theme={theme}>
        <Line position="x*y" color="category" />
      </Chart>
    </div>
  );
}

Context HOCs

Higher-order components for providing chart and view context to components outside the chart tree.

/**
 * HOC to provide chart instance context
 * @param Component - React component to wrap
 * @returns Enhanced component with chart instance access
 */
function withChartInstance<P>(Component: React.ComponentType<P>): React.ComponentType<P>;

/**
 * HOC to provide view context  
 * @param Component - React component to wrap
 * @returns Enhanced component with view access
 */
function withView<P>(Component: React.ComponentType<P>): React.ComponentType<P>;

Usage Examples:

import React from "react";
import { withChartInstance, withView } from "bizcharts";

// Component enhanced with chart instance
const ChartControlsBase = ({ chartInstance, onExport }) => {
  const handleExport = () => {
    if (chartInstance) {
      const dataURL = chartInstance.toDataURL();
      onExport(dataURL);
    }
  };

  return (
    <div>
      <button onClick={handleExport}>Export Chart</button>
    </div>
  );
};

const ChartControls = withChartInstance(ChartControlsBase);

// Component enhanced with view
const ViewControlsBase = ({ view, onFilter }) => {
  const handleFilter = (category) => {
    if (view) {
      view.filter('category', (val) => val === category);
      view.render();
      onFilter(category);
    }
  };

  return (
    <div>
      <button onClick={() => handleFilter('A')}>Filter A</button>
      <button onClick={() => handleFilter('B')}>Filter B</button>
    </div>
  );
};

const ViewControls = withView(ViewControlsBase);

// Usage in chart
function EnhancedChart() {
  return (
    <Chart height={400} data={data} autoFit>
      <Line position="x*y" color="category" />
      <ChartControls onExport={(url) => console.log('Exported:', url)} />
      <ViewControls onFilter={(cat) => console.log('Filtered:', cat)} />
    </Chart>
  );
}

Hook Combinations

Advanced patterns combining multiple hooks for complex chart interactions.

// Combined hook usage
function AdvancedChartManager() {
  const chart = useChartInstance();
  const view = useView();
  const [theme, setTheme] = useTheme();

  useEffect(() => {
    if (chart && view) {
      // Setup complex interactions between chart and view
      chart.on('plot:click', (e) => {
        // Update view based on chart interaction
        const data = view.getData();
        const filtered = data.filter(d => d.value > 50);
        view.changeData(filtered);
      });

      // Theme-based customization
      if (theme.name === 'dark') {
        chart.axis('x', {
          label: { style: { fill: '#fff' } }
        });
      }
    }
  }, [chart, view, theme]);

  return (
    <div>
      <button onClick={() => setTheme('dark')}>Dark Mode</button>
      <button onClick={() => setTheme('light')}>Light Mode</button>
    </div>
  );
}

Types

// G2 Chart instance type (re-exported from @antv/g2)
interface Chart {
  // Canvas and size
  getSize(): { width: number; height: number };
  changeSize(width: number, height: number): void;
  
  // Data operations
  data(data: any[]): Chart;
  changeData(data: any[]): void;
  
  // Rendering
  render(): void;
  clear(): void;
  destroy(): void;
  
  // Export
  toDataURL(): string;
  downloadImage(name?: string): void;
  
  // Events
  on(eventName: string, callback: Function): void;
  off(eventName: string, callback: Function): void;
  emit(eventName: string, ...args: any[]): void;
  
  // Interactions
  interaction(name: string, cfg?: any): void;
  removeInteraction(name: string): void;
  
  // Annotations
  annotation(): any;
  
  // Axes
  axis(field: string, cfg: any): Chart;
  
  // Coordinate
  coordinate(type?: string, cfg?: any): Chart;
  
  // Other G2 Chart methods
  [key: string]: any;
}

// G2 View instance type (re-exported from @antv/g2)
interface View {
  // Data operations
  data(data: any[]): View;
  changeData(data: any[]): void;
  getData(): any[];
  
  // Filtering
  filter(field: string, condition: Function | any): View;
  
  // Rendering
  render(): void;
  
  // Coordinate
  coordinate(type?: string, cfg?: any): View;
  
  // Interactions
  interaction(name: string, cfg?: any): void;
  
  // Other G2 View methods
  [key: string]: any;
}

// Theme object structure
interface Theme {
  name?: string;
  colors10?: string[];
  colors20?: string[];
  backgroundColor?: string;
  subColor?: string;
  semanticRed?: string;
  semanticGreen?: string;
  [key: string]: any;
}

// Hook return types
type UseChartInstanceReturn = Chart;
type UseViewReturn = View;
type UseThemeReturn = [Theme, (themeName: string | Theme) => void];

// HOC prop injection types
interface WithChartInstanceProps {
  chartInstance?: Chart;
}

interface WithViewProps {
  view?: View;
}