ZIndexLayer

A layer that renders its children into a portal corresponding to the given zIndex. We can't use regular CSS z-index because SVG does not support it. So instead, we create separate DOM nodes for each zIndex layer and render the children into the corresponding DOM node using React portals.

This component must be used inside a Chart component.

Available since Recharts 3.4

import {
  Bar,
  BarChart,
  CartesianGrid,
  DefaultZIndexes,
  Tooltip,
  useActiveTooltipDataPoints,
  usePlotArea,
  XAxis,
  YAxis,
  ZIndexLayer,
} from 'recharts';
import { RechartsDevtools } from '@recharts/devtools';

type DataPoint = { month: string; revenue: number };

const data: Array<DataPoint> = [
  { month: 'Jan', revenue: 4200 },
  { month: 'Feb', revenue: 5800 },
  { month: 'Mar', revenue: 7200 },
  { month: 'Apr', revenue: 6100 },
  { month: 'May', revenue: 8900 },
  { month: 'Jun', revenue: 7400 },
];

/**
 * `usePlotArea` reports where the drawable area sits after axes and legends
 * have taken their space, so custom elements can position themselves against it.
 */
function PlotAreaFrame() {
  const plotArea = usePlotArea();

  if (plotArea == null) {
    return null;
  }

  return <rect {...plotArea} fill="none" stroke="#64748b" strokeDasharray="4 4" />;
}

/**
 * Chart state is available to any component inside the chart, so you can render
 * your own readouts without going through Tooltip at all.
 */
function ActiveReadout() {
  const plotArea = usePlotArea();
  const activePoints = useActiveTooltipDataPoints<DataPoint>();
  const point = activePoints?.[0];

  if (plotArea == null || point == null) {
    return null;
  }

  return (
    // Position the element above Tooltip cursor so that it's not covered behind it
    <ZIndexLayer zIndex={DefaultZIndexes.cursorRectangle + 1}>
      <text x={plotArea.x + 10} y={plotArea.y + 22} fill="#0ea5e9" fontSize={16} fontWeight={700}>
        {point.month}: {point.revenue}
      </text>
    </ZIndexLayer>
  );
}

export default function CustomizeCustomElement() {
  return (
    <BarChart
      style={{ width: '100%', maxWidth: 600, maxHeight: '70vh', aspectRatio: 1.618 }}
      responsive
      data={data}
      margin={{ top: 20, right: 30, left: 20, bottom: 5 }}
    >
      <CartesianGrid />
      <XAxis dataKey="month" />
      <YAxis />
      <Tooltip defaultIndex={4} />
      <Bar dataKey="revenue" stroke="none" fill="#0ea5e9" />
      {/* Your own components are ordinary chart children - no wrapper component needed. */}
      <PlotAreaFrame />
      <ActiveReadout />
      <RechartsDevtools />
    </BarChart>
  );
}
import React, { useRef, useEffect, useState } from 'react';
import ReactDOM from 'react-dom/client';
import { Legend, Pie, PieChart, Tooltip } from 'recharts';
import { RechartsDevtools } from '@recharts/devtools';

// #region shadow DOM wrapper component, and data
interface ShadowDomWrapperProps {
  children: React.ReactNode;
}

const ShadowDomWrapper: React.FC<ShadowDomWrapperProps> = ({ children }) => {
  const hostRef = useRef<HTMLDivElement>(null);
  const [shadowRoot, setShadowRoot] = useState<ShadowRoot | null>(null);

  useEffect(() => {
    if (hostRef.current && !hostRef.current.shadowRoot) {
      const shadow = hostRef.current.attachShadow({ mode: 'closed' });
      setShadowRoot(shadow);
    }
  }, []);

  useEffect(() => {
    if (shadowRoot) {
      // Clear existing content
      shadowRoot.innerHTML = '';

      // Create a container for React to render into
      const container = document.createElement('div');
      container.id = 'shadow-container';
      shadowRoot.appendChild(container);

      // Render children into the shadow DOM
      const root = ReactDOM.createRoot(container);
      root.render(children);

      return () => {
        root.unmount();
      };
    }
    return () => {};
  }, [shadowRoot, children]);

  return <div ref={hostRef} className="shadow-host" />;
};

const pieData = [
  { name: 'Desktop', value: 400, fill: '#0088FE' },
  { name: 'Mobile', value: 300, fill: '#00C49F' },
  { name: 'Tablet', value: 200, fill: '#FFBB28' },
  { name: 'Other', value: 100, fill: '#FF8042' },
];
// #endregion

export default function ShadowDomExample({ isAnimationActive = true }: { isAnimationActive?: boolean }) {
  return (
    <ShadowDomWrapper>
      <PieChart width={380} height={300}>
        <Pie
          data={pieData}
          cx="50%"
          cy="50%"
          labelLine={false}
          label={({ name, percent }) => `${name} ${((percent ?? 0) * 100).toFixed(0)}%`}
          outerRadius={100}
          dataKey="value"
          isAnimationActive={isAnimationActive}
        />
        <Tooltip />
        <Legend />
        <RechartsDevtools />
      </PieChart>
    </ShadowDomWrapper>
  );
}

  • zIndexnumber

    Z-Index of this component and its children.

    The higher the value, the more on top it will be rendered. Components with higher zIndex will appear in front of components with lower zIndex.

    If undefined or 0, the content is rendered in the default layer without portals.

  • childrenReactNodeoptional

    The content to render inside this zIndex layer. Undefined children are allowed and will render nothing and will still report the zIndex to the portal system.