CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-recharts

React charting library with declarative, composable components for building interactive data visualizations

Pending
Overview
Eval results
Files

hooks-utilities.mddocs/

Hooks and Utilities

React hooks for accessing chart state and utility functions for custom chart development. These tools provide access to chart layout information, tooltip data, and helper functions for advanced chart customization.

Capabilities

Chart State Hooks

useActiveTooltipLabel

Hook for accessing the currently active tooltip label from chart data.

/**
 * Returns the active tooltip label from chart interactions
 * @returns Currently active tooltip label or undefined if no interaction
 */
function useActiveTooltipLabel(): string | undefined;

Usage Example:

import { useActiveTooltipLabel } from 'recharts';

function CustomTooltipComponent() {
  const activeLabel = useActiveTooltipLabel();
  
  return (
    <div>
      {activeLabel && <p>Current Label: {activeLabel}</p>}
    </div>
  );
}

useActiveTooltipDataPoints

Hook for accessing the currently active data points being displayed in the tooltip.

/**
 * Returns the currently active data points visible in tooltip
 * @returns Array of data points currently visible in tooltip, or undefined if no interaction
 */
function useActiveTooltipDataPoints<T = unknown>(): ReadonlyArray<T> | undefined;

Usage Example:

import { useActiveTooltipDataPoints } from 'recharts';

function CustomTooltipComponent() {
  const dataPoints = useActiveTooltipDataPoints();
  
  return (
    <div>
      {dataPoints?.map((point, index) => (
        <div key={index}>Value: {point.value}</div>
      ))}
    </div>
  );
}

Layout Information Hooks

useOffset

Hook for accessing chart offset information (distances between chart edges and plot area).

/**
 * Returns chart offset defining blank space between chart and plot area
 * @returns Chart offset in pixels, or undefined if used outside chart context
 */
function useOffset(): ChartOffset | undefined;

Usage Example:

import { useOffset } from 'recharts';

function CustomChartComponent() {
  const offset = useOffset();
  
  if (offset) {
    console.log(`Chart margins: top=${offset.top}, right=${offset.right}, bottom=${offset.bottom}, left=${offset.left}`);
  }
  
  return <div>Custom component with offset info</div>;
}

usePlotArea

Hook for accessing plot area dimensions and position where actual chart data is rendered.

/**
 * Returns plot area dimensions and position for data rendering area
 * @returns Plot area coordinates and dimensions, or undefined if used outside chart context
 */
function usePlotArea(): PlotArea | undefined;

Usage Example:

import { usePlotArea } from 'recharts';

function CustomOverlay() {
  const plotArea = usePlotArea();
  
  if (!plotArea) return null;
  
  return (
    <rect
      x={plotArea.x}
      y={plotArea.y}
      width={plotArea.width}
      height={plotArea.height}
      fill="transparent"
      stroke="#ddd"
      strokeDasharray="5,5"
    />
  );
}

useChartWidth

Hook for accessing the current chart width in pixels.

/**
 * Returns the width of the chart container in pixels
 * @returns Chart width in pixels, or undefined if used outside chart context
 */
function useChartWidth(): number | undefined;

useChartHeight

Hook for accessing the current chart height in pixels.

/**
 * Returns the height of the chart container in pixels
 * @returns Chart height in pixels, or undefined if used outside chart context
 */
function useChartHeight(): number | undefined;

Usage Example:

import { useChartWidth, useChartHeight } from 'recharts';

function ResponsiveCustomComponent() {
  const width = useChartWidth();
  const height = useChartHeight();
  
  return (
    <text x={width ? width / 2 : 0} y={height ? height / 2 : 0} textAnchor="middle">
      Chart Size: {width} × {height}
    </text>
  );
}

Utility Functions

getNiceTickValues

Utility function for calculating aesthetically pleasing tick values for chart axes.

/**
 * Calculates nice tick values for axis scales
 * @param domain - Data domain [min, max]
 * @param tickCount - Desired number of ticks
 * @param allowDecimals - Whether to allow decimal tick values
 * @returns Array of nice tick values
 */
function getNiceTickValues(
  domain: [number, number], 
  tickCount?: number, 
  allowDecimals?: boolean
): number[];

Usage Example:

import { getNiceTickValues } from 'recharts';

// Calculate nice tick values for a domain
const domain: [number, number] = [0, 847];
const ticks = getNiceTickValues(domain, 5, true);
// Result might be: [0, 200, 400, 600, 800, 1000]

// Use in custom axis
<YAxis 
  domain={domain}
  ticks={ticks}
  tickCount={ticks.length}
/>

Global Configuration

Global configuration object for library-wide settings.

/**
 * Global configuration object with library settings
 */
interface Global {
  /** Server-side rendering detection flag */
  isSsr: boolean;
}

const Global: Global;

Usage Example:

import { Global } from 'recharts';

// Check if running in server-side rendering environment
if (Global.isSsr) {
  console.log('Running in SSR environment');
}

Hook Types and Interfaces

ChartOffset

Interface defining the offset/margin space around the chart plot area.

/**
 * Defines the blank space between the chart container and plot area
 */
interface ChartOffset {
  /** Distance from top edge of chart to top edge of plot area */
  readonly top: number;
  /** Distance from bottom edge of chart to bottom edge of plot area */
  readonly bottom: number;
  /** Distance from left edge of chart to left edge of plot area */
  readonly left: number;
  /** Distance from right edge of chart to right edge of plot area */
  readonly right: number;
}

PlotArea

Interface defining the plot area where actual chart data is rendered.

/**
 * Defines the area where actual chart data is rendered
 */
interface PlotArea {
  /** Width of the plot area */
  readonly width: number;
  /** Height of the plot area */
  readonly height: number;
  /** X coordinate of the top-left corner of plot area */
  readonly x: number;
  /** Y coordinate of the top-left corner of plot area */
  readonly y: number;
}

Advanced Hook Usage Patterns

Custom Tooltip with Hooks

import { 
  useActiveTooltipLabel, 
  useActiveTooltipDataPoints, 
  usePlotArea 
} from 'recharts';

function AdvancedCustomTooltip() {
  const label = useActiveTooltipLabel();
  const dataPoints = useActiveTooltipDataPoints();
  const plotArea = usePlotArea();
  
  if (!label || !dataPoints || dataPoints.length === 0) {
    return null;
  }
  
  return (
    <div className="custom-tooltip" style={{
      position: 'absolute',
      background: 'white',
      border: '1px solid #ccc',
      padding: '10px',
      borderRadius: '4px'
    }}>
      <h4>{label}</h4>
      {dataPoints.map((point, index) => (
        <div key={index}>
          <span style={{ color: point.color }}>●</span>
          {point.name}: {point.value}
        </div>
      ))}
    </div>
  );
}

Custom Chart Overlay with Layout Info

import { useOffset, usePlotArea, useChartWidth, useChartHeight } from 'recharts';

function ChartOverlay() {
  const offset = useOffset();
  const plotArea = usePlotArea();
  const chartWidth = useChartWidth();
  const chartHeight = useChartHeight();
  
  if (!offset || !plotArea || !chartWidth || !chartHeight) {
    return null;
  }
  
  return (
    <g>
      {/* Plot area border */}
      <rect
        x={plotArea.x}
        y={plotArea.y}
        width={plotArea.width}
        height={plotArea.height}
        fill="none"
        stroke="#e0e0e0"
        strokeDasharray="2,2"
      />
      
      {/* Chart info text */}
      <text x={10} y={20} fontSize="12" fill="#666">
        Chart: {chartWidth}×{chartHeight} | Plot: {plotArea.width}×{plotArea.height}
      </text>
    </g>
  );
}

Using Hooks in Custom Shapes

import { usePlotArea } from 'recharts';

function CustomBackground() {
  const plotArea = usePlotArea();
  
  if (!plotArea) return null;
  
  // Create gradient background for plot area
  return (
    <defs>
      <linearGradient id="plotGradient" x1="0%" y1="0%" x2="0%" y2="100%">
        <stop offset="0%" stopColor="#f8f9fa" />
        <stop offset="100%" stopColor="#ffffff" />
      </linearGradient>
      <rect
        x={plotArea.x}
        y={plotArea.y}
        width={plotArea.width}
        height={plotArea.height}
        fill="url(#plotGradient)"
      />
    </defs>
  );
}

Context Requirements

Important: All hooks must be used within a chart context (inside a chart component like LineChart, BarChart, etc.). Using these hooks outside of a chart context will return undefined.

// ✅ Correct usage - inside chart
<LineChart data={data}>
  <CustomComponentUsingHooks />
</LineChart>

// ❌ Incorrect usage - outside chart context  
<div>
  <CustomComponentUsingHooks /> {/* Hooks will return undefined */}
</div>

Install with Tessl CLI

npx tessl i tessl/npm-recharts

docs

cartesian-components.md

charts.md

components.md

hooks-utilities.md

index.md

polar-components.md

shapes.md

tile.json