API reference
Hooks
React hooks that read from Chartlyx’s internal contexts. Use these to build custom components that participate in the chart layout: crosshairs, annotations, custom hover UI, markers.
useChartContext
useChartContext<T>(): ChartContextValue<T>
Read the Cartesian chart context. Must be called inside a
<ChartContainer> subtree; throws otherwise. Generic
over your row type so data is typed as
readonly T[].
import { useChartContext } from "chartlyx";
interface Row { month: string; revenue: number }
function MyMarker() {
const {
data, // readonly Row[]
xAccessor, // (d: Row) => number | Date | string
yAccessor, // (d: Row) => number | Date | string
xScale,
yScale,
width, height, // full container dimensions
innerWidth, // width minus horizontal margins
innerHeight, // height minus vertical margins
margin, // { top, right, bottom, left }
} = useChartContext<Row>();
return data.map((d, i) => (
<circle
key={i}
cx={xScale(xAccessor(d))}
cy={yScale(yAccessor(d))}
r={4}
fill="tomato"
/>
));
} Returned value
data: readonly T[]: the rows passed to the container.xScale, yScale: D3 scale functions with margins baked in.xAccessor, yAccessor: resolved fromxKey/xandyKey/y.width, height: measured container size in pixels.innerWidth, innerHeight: the plottable area (dimensions minus margins).margin: the final margin object (defaults merged with your override).
Errors
Calling outside a <ChartContainer> throws
"useChartContext must be used inside a <ChartContainer>".
usePolarChartContext
usePolarChartContext<T>(): PolarChartContextValue<T>
Read the polar chart context. Must be called inside a
<PolarChartContainer> subtree; throws otherwise.
Generic over your row type; both data and
valueAccessor are typed to T.
import { usePolarChartContext } from "chartlyx";
interface Row { category: string; revenue: number }
function CenterLabel() {
const {
data, // readonly Row[]
valueAccessor, // (d: Row) => number
cx, cy, // center of the chart
radius, // outer radius in pixels
innerRadius, // inner radius (0 for pie, >0 for donut)
padding, // gap from container edge
width, height, // full container dimensions
activeIndex, // number | null: which slice is hovered
setActiveIndex, // (i: number | null) => void
} = usePolarChartContext<Row>();
const total = data.reduce((sum, d) => sum + valueAccessor(d), 0);
return (
<text x={cx} y={cy} textAnchor="middle" dy="0.32em" fill="#f8fafc">
${total.toLocaleString()}
</text>
);
} Returned value
data: readonly T[],valueAccessor: (d: T) => number: both narrowed toT.cx, cy: center coordinates.radius, innerRadius: outer and inner radius.padding, width, height: container geometry.activeIndex: index of the currently-hovered slice/polygon, ornull.setActiveIndex: setter for custom hover targets (e.g. a legend that highlights on hover).