### Installation
Source: https://github.com/airbnb/visx/blob/master/packages/visx-tooltip/Readme.md
Install the @visx/tooltip package using npm.
```APIDOC
## Installation
```
npm install --save @visx/tooltip
```
```
--------------------------------
### Installation
Source: https://github.com/airbnb/visx/blob/master/packages/visx-mock-data/Readme.md
Install the @visx/mock-data package using npm.
```APIDOC
## Installation
Install the @visx/mock-data package using npm.
```bash
npm install --save @visx/mock-data
```
```
--------------------------------
### Install @visx/theme
Source: https://github.com/airbnb/visx/blob/master/packages/visx-theme/Readme.md
Install the @visx/theme package using npm.
```sh
npm install --save @visx/theme
```
--------------------------------
### Install @visx/responsive
Source: https://github.com/airbnb/visx/blob/master/packages/visx-responsive/Readme.md
Install the @visx/responsive package using npm.
```bash
npm install --save @visx/responsive
```
--------------------------------
### Install @visx/pattern
Source: https://github.com/airbnb/visx/blob/master/packages/visx-pattern/Readme.md
Command to install the package via npm.
```bash
npm install --save @visx/pattern
```
--------------------------------
### Install @visx/visx
Source: https://github.com/airbnb/visx/blob/master/packages/visx-visx/Readme.md
Use npm to install the @visx/visx package. This command installs the main package, which includes all other visx packages.
```bash
npm install --save @visx/visx
```
--------------------------------
### Install @visx/chart
Source: https://github.com/airbnb/visx/blob/master/packages/visx-chart/Readme.md
Install the @visx/chart package using npm.
```sh
npm install --save @visx/chart
```
--------------------------------
### Install Yarn and Clone visx
Source: https://github.com/airbnb/visx/blob/master/CONTRIBUTING.md
Installs Yarn, clones the visx repository, and installs project dependencies.
```sh
# Install `yarn`, alternatives at https://yarnpkg.com/en/docs/install
curl -o- -L https://yarnpkg.com/install.sh | bash
# Clone or fork `visx`
git clone git@github.com:airbnb/visx.git # or your fork
cd visx
# install dependencies, and have `yarn` symlink within-`visx` dependencies
yarn
```
--------------------------------
### Install visx Packages for Bar Graph
Source: https://github.com/airbnb/visx/blob/master/README.md
Install necessary visx packages including mock data, group, shape, and scale for creating visualizations. This command installs the packages required for the bar graph example.
```bash
npm install --save @visx/mock-data @visx/group @visx/shape @visx/scale
```
--------------------------------
### Install @visx/mock-data
Source: https://github.com/airbnb/visx/blob/master/packages/visx-mock-data/Readme.md
Install the @visx/mock-data package using npm.
```bash
npm install --save @visx/mock-data
```
--------------------------------
### Install @visx/bounds
Source: https://github.com/airbnb/visx/blob/master/packages/visx-bounds/Readme.md
Install the @visx/bounds package using npm.
```bash
npm install --save @visx/bounds
```
--------------------------------
### Install @visx/kernel
Source: https://github.com/airbnb/visx/blob/master/packages/visx-kernel/Readme.md
Install the @visx/kernel package using npm.
```sh
npm install --save @visx/kernel
```
--------------------------------
### Install @visx/scale
Source: https://github.com/airbnb/visx/blob/master/packages/visx-scale/Readme.md
Command to install the package via npm.
```sh
npm install --save @visx/scale
```
--------------------------------
### Install @visx/delaunay
Source: https://github.com/airbnb/visx/blob/master/packages/visx-delaunay/Readme.md
Install the @visx/delaunay package using npm.
```bash
npm install --save @visx/delaunay
```
--------------------------------
### Install @visx/shape
Source: https://github.com/airbnb/visx/blob/master/README.md
Install the @visx/shape package to get started with visx components. This is the current stable release and requires React 18 or 19.
```bash
npm install @visx/shape
```
--------------------------------
### Install @visx/network
Source: https://github.com/airbnb/visx/blob/master/packages/visx-network/Readme.md
Command to install the package via npm.
```bash
npm install --save @visx/network
```
--------------------------------
### Initialize various scale types
Source: https://github.com/airbnb/visx/blob/master/packages/visx-scale/Readme.md
Examples of initializing different scale types provided by @visx/scale.
```js
const scale = Scale.scaleBand({
/*
range,
round,
domain,
padding,
nice = false
*/
});
```
```js
const scale = Scale.scaleLinear({
/*
range,
round,
domain,
nice = false,
clamp = false,
*/
});
```
```js
const scale = Scale.scaleLog({
/*
range,
round,
domain,
base,
nice = false,
clamp = false,
*/
});
```
```js
const scale = Scale.scaleRadial({
/*
range,
round,
domain,
nice = false,
clamp = false,
*/
});
```
```js
const scale = Scale.scaleOrdinal({
/*
range,
domain,
unknown,
*/
});
```
```js
const scale = Scale.scalePoint({
/*
range,
round,
domain,
padding,
align,
nice = false,
*/
});
```
```js
const scale = Scale.scalePower({
/*
range,
round,
domain,
exponent,
nice = false,
clamp = false,
*/
});
```
```js
// No need to set the exponent, It is always 0.5
const scale = Scale.scaleSqrt({
/*
range,
round,
domain,
nice = false,
clamp = false,
*/
});
```
```js
const scale = Scale.scaleTime({
/*
range,
round,
domain,
nice = false,
clamp = false,
*/
});
```
```js
const scale = Scale.scaleUtc({
/*
range,
round,
domain,
nice = false,
clamp = false,
*/
});
```
--------------------------------
### Install @visx/legend
Source: https://github.com/airbnb/visx/blob/master/packages/visx-legend/Readme.md
Install the @visx/legend package using npm.
```bash
npm install --save @visx/legend
```
--------------------------------
### Install @visx/chord
Source: https://github.com/airbnb/visx/blob/master/packages/visx-chord/Readme.md
Use this command to install the package via npm.
```bash
npm install --save @visx/chord
```
--------------------------------
### Install @visx/grid Package
Source: https://github.com/airbnb/visx/blob/master/packages/visx-grid/Readme.md
Install the @visx/grid package using npm. This is a prerequisite for using the grid components in your project.
```bash
npm install --save @visx/grid
```
--------------------------------
### Install @visx/voronoi
Source: https://github.com/airbnb/visx/blob/master/packages/visx-voronoi/Readme.md
Command to install the package via npm.
```bash
npm install --save @visx/voronoi
```
--------------------------------
### Install @visx/a11y
Source: https://github.com/airbnb/visx/blob/master/packages/visx-a11y/Readme.md
Install the @visx/a11y package using npm.
```sh
npm install --save @visx/a11y
```
--------------------------------
### Install @visx/clip-path
Source: https://github.com/airbnb/visx/blob/master/packages/visx-clip-path/Readme.md
Install the @visx/clip-path package using npm. This is the first step to using the clip path utilities in your project.
```bash
npm install --save @visx/clip-path
```
--------------------------------
### Implement Voronoi Layout and Polygon Rendering
Source: https://github.com/airbnb/visx/blob/master/packages/visx-voronoi/Readme.md
Example showing how to initialize the voronoi layout and render polygons using the VoronoiPolygon component.
```javascript
import { voronoi, VoronoiPolygon } from '@visx/voronoi';
const points = Array(n).fill(null).map(() => ({
x: Math.random() * innerWidth,
y: Math.random() * innerHeight,
}));
// width + height set an extent on the voronoi
// x + y set relevant accessors depending on the shape of your data
const voronoiLayout = voronoi({
x: d => d.x,
y: d => d.y,
width,
height,
});
const voronoiDiagram = voronoiLayout(data);
const polygons = voronoiDiagram.polygons(); // equivalent to voronoiLayout.polygons(points)
return (
)
```
--------------------------------
### Install @visx/text
Source: https://github.com/airbnb/visx/blob/master/packages/visx-text/Readme.md
Command to install the package via npm.
```bash
npm install --save @visx/text
```
--------------------------------
### Install @visx/hierarchy
Source: https://github.com/airbnb/visx/blob/master/packages/visx-hierarchy/Readme.md
Command to install the package via npm.
```bash
npm install --save @visx/hierarchy
```
--------------------------------
### Install @visx/gradient
Source: https://github.com/airbnb/visx/blob/master/packages/visx-gradient/Readme.md
Command to install the package via npm.
```bash
npm install --save @visx/gradient
```
--------------------------------
### Install @visx/group
Source: https://github.com/airbnb/visx/blob/master/packages/visx-group/Readme.md
Install the @visx/group package using npm. This is the first step to using the group component.
```bash
npm install --save @visx/group
```
--------------------------------
### Install @visx/annotation
Source: https://github.com/airbnb/visx/blob/master/packages/visx-annotation/Readme.md
Standard npm installation command for the @visx/annotation package.
```bash
npm install --save @visx/annotation
```
--------------------------------
### Install @visx/event
Source: https://github.com/airbnb/visx/blob/master/packages/visx-event/Readme.md
Use npm to add the package to your project dependencies.
```bash
npm install --save @visx/event
```
--------------------------------
### Install @visx/curve
Source: https://github.com/airbnb/visx/blob/master/packages/visx-curve/Readme.md
Install the @visx/curve package using npm.
```bash
npm install --save @visx/curve
```
--------------------------------
### Install @visx/zoom
Source: https://github.com/airbnb/visx/blob/master/packages/visx-zoom/Readme.md
Use this command to add the @visx/zoom package to your project dependencies.
```bash
npm install --save @visx/zoom
```
--------------------------------
### Install @visx/geo
Source: https://github.com/airbnb/visx/blob/master/packages/visx-geo/Readme.md
Install the @visx/geo package using npm.
```bash
npm install --save @visx/geo
```
--------------------------------
### Install @visx/tooltip
Source: https://github.com/airbnb/visx/blob/master/packages/visx-tooltip/Readme.md
Install the @visx/tooltip package using npm. This package provides utilities for adding tooltips to your visualizations.
```bash
npm install --save @visx/tooltip
```
--------------------------------
### Install @visx/point
Source: https://github.com/airbnb/visx/blob/master/packages/visx-point/Readme.md
Use npm to add the package to your project dependencies.
```bash
npm install --save @visx/point
```
--------------------------------
### Example: Functional Component with Tooltip
Source: https://github.com/airbnb/visx/blob/master/packages/visx-tooltip/Readme.md
An example demonstrating the usage of useTooltip and useTooltipInPortal hooks for creating interactive tooltips within a functional React component.
```APIDOC
## Example: Functional Component with Tooltip
### Description
This example shows how to integrate `useTooltip` and `useTooltipInPortal` to display tooltips based on user interactions within a chart.
### Code
```jsx
import { useTooltip, useTooltipInPortal, TooltipWithBounds } from '@visx/tooltip';
import { localPoint } from '@visx/event';
const ChartWithTooltip = () => {
const {
tooltipData,
tooltipLeft,
tooltipTop,
tooltipOpen,
showTooltip,
hideTooltip,
} = useTooltip();
// If you don't want to use a Portal, simply replace `TooltipInPortal` below with
// `Tooltip` or `TooltipWithBounds` and remove `containerRef`
const { containerRef, TooltipInPortal } = useTooltipInPortal({
// use TooltipWithBounds
detectBounds: true,
// when tooltip containers are scrolled, this will correctly update the Tooltip position
scroll: true,
})
const handleMouseOver = (event, datum) => {
const coords = localPoint(event.target.ownerSVGElement, event);
showTooltip({
tooltipLeft: coords.x,
tooltipTop: coords.y,
tooltipData: datum
});
};
return (
// Set `ref={containerRef}` on the element corresponding to the coordinate system that
// `left/top` (passed to `TooltipInPortal`) are relative to.
<>
{tooltipOpen && (
Data value {tooltipData}
)}
>
)
};
render(, document.getElementById("root"));
```
```
--------------------------------
### Install visx XYChart and react-spring
Source: https://github.com/airbnb/visx/blob/master/packages/visx-xychart/README.md
Install the necessary packages for using visx XYChart. react-spring is a peer dependency for animated components.
```bash
npm install --save @visx/xychart react-spring
```
--------------------------------
### Install @visx/heatmap
Source: https://github.com/airbnb/visx/blob/master/packages/visx-heatmap/Readme.md
Install the @visx/heatmap package using npm. This command adds the package to your project's dependencies.
```bash
npm install --save @visx/heatmap
```
--------------------------------
### Install d3-scale-chromatic
Source: https://github.com/airbnb/visx/blob/master/packages/visx-scale/Readme.md
Install the required dependency for color schemes via npm.
```sh
npm install --save d3-scale-chromatic
```
--------------------------------
### Install @visx/sankey
Source: https://github.com/airbnb/visx/blob/master/packages/visx-sankey/Readme.md
Use npm to add the package to your project dependencies.
```bash
npm install --save @visx/sankey
```
--------------------------------
### Install Visx 4.x with npm
Source: https://github.com/airbnb/visx/blob/master/MIGRATION.md
Use npm to install the latest major version of @visx/shape and @visx/scale. Ensure all visx packages are upgraded simultaneously.
```bash
npm install @visx/shape@^4 @visx/scale@^4
```
--------------------------------
### XYChart with Tooltip (Imported Polyfill)
Source: https://github.com/airbnb/visx/blob/master/packages/visx-xychart/README.md
Example of using XYChart with Tooltip after importing the resize-observer-polyfill. This is useful if the target browser does not support ResizeObserver natively.
```tsx
// import the polyfill in the needed module, or set it on `window` object
import ResizeObserver from 'resize-observer-polyfill';
() => // 😎
```
--------------------------------
### XYChart Event Handling Example
Source: https://github.com/airbnb/visx/blob/master/packages/visx-xychart/README.md
Demonstrates how to handle pointer events like onPointerMove, onPointerOut, onPointerUp, and onPointerDown at the chart or series level. Also shows how to enable keyboard accessibility with onFocus and onBlur handlers.
```typescript
type EventHandlerParams = {
datum: Datum; // nearest Datum to event, for Series with `dataKey=key`
distanceX: number; // x distance between event and Datum, in px
distanceY;: number; // y distance between event and Datum, in px
event: React.PointerEvent | React.FocusEvent; // the event
index: number; // index of Datum in Series `data` array
key: string; // `dataKey` of Series to which `Datum` belongs
svgPoint: { x: number; y: number }; // event position in svg-coordinates
};
```
--------------------------------
### XYChart with Tooltip (No Polyfill, Browser Support)
Source: https://github.com/airbnb/visx/blob/master/packages/visx-xychart/README.md
Example of using XYChart with Tooltip when the target browser supports ResizeObserver natively. No polyfill is needed.
```tsx
() =>
```
--------------------------------
### Add @types/react-dom as a dev dependency
Source: https://github.com/airbnb/visx/blob/master/MIGRATION.md
If using @visx/bounds, @visx/tooltip, @visx/xychart, or the @visx/visx meta-package, also install @types/react-dom as a development dependency.
```bash
yarn add -D @types/react-dom
```
--------------------------------
### XYChart without Tooltip (No Polyfill, Browser Support)
Source: https://github.com/airbnb/visx/blob/master/packages/visx-xychart/README.md
Example of using XYChart without a Tooltip when the target browser supports ResizeObserver natively. No polyfill is needed.
```tsx
() =>
```
--------------------------------
### XYChart with Tooltip (ResizeObserver Polyfill Prop)
Source: https://github.com/airbnb/visx/blob/master/packages/visx-xychart/README.md
Example of cleanly passing a ResizeObserver polyfill to the XYChart component using the `resizeObserverPolyfill` prop. This ensures the polyfill is available to child Tooltip and AnnotationLabel components.
```tsx
// cleanly pass polyfill to component that needs it
import ResizeObserver from 'resize-observer-polyfill';
() => (
)
```
--------------------------------
### Implement Tooltip with useTooltipInPortal
Source: https://github.com/airbnb/visx/blob/master/packages/visx-tooltip/Readme.md
A functional component example demonstrating how to use useTooltipInPortal to manage tooltip state and positioning within a React component.
```jsx
import { useTooltip, useTooltipInPortal, TooltipWithBounds } from '@visx/tooltip';
import { localPoint } from '@visx/event';
const ChartWithTooltip = () => {
const {
tooltipData,
tooltipLeft,
tooltipTop,
tooltipOpen,
showTooltip,
hideTooltip,
} = useTooltip();
// If you don't want to use a Portal, simply replace `TooltipInPortal` below with
// `Tooltip` or `TooltipWithBounds` and remove `containerRef`
const { containerRef, TooltipInPortal } = useTooltipInPortal({
// use TooltipWithBounds
detectBounds: true,
// when tooltip containers are scrolled, this will correctly update the Tooltip position
scroll: true,
})
const handleMouseOver = (event, datum) => {
const coords = localPoint(event.target.ownerSVGElement, event);
showTooltip({
tooltipLeft: coords.x,
tooltipTop: coords.y,
tooltipData: datum
});
};
return (
// Set `ref={containerRef}` on the element corresponding to the coordinate system that
// `left/top` (passed to `TooltipInPortal`) are relative to.
<>
{tooltipOpen && (
Data value {tooltipData}
)}
>
)
};
render(, document.getElementById("root"));
```
--------------------------------
### XYChart Annotations Integration
Source: https://github.com/airbnb/visx/blob/master/packages/visx-xychart/README.md
Shows how to integrate @visx/annotations with @visx/xychart to annotate individual points or thresholds. This example demonstrates using AnnotationCircleSubject and AnnotationConnector.
```tsx
import React from 'react';
import {
Annotation,
AnnotationLabel,
AnnotationConnector,
AnnotationCircleSubject,
Grid,
LineSeries,
XYChart,
} from '@visx/xychart';
const data = [
{ x: '2020-01-01', y: 50 },
{ x: '2020-01-02', y: 10 },
{ x: '2020-01-03', y: 20 },
{ x: '2020-01-04', y: 5 },
];
const labelXOffset = -40;
const labelYOffset = -50;
const chartConfig = {
xScale: { type: 'band' },
yScale: { type: 'linear' },
height: 300,
margin: { top: 10, right: 10, bottom: 10, left: 10 },
};
export default () => (
d.x} yAccessor={d => d.y} />
{/** Text label **/
{/** Draw circle around point **/
{/** Connect label to CircleSubject **/
);
```
--------------------------------
### EventEmitterProvider Example
Source: https://github.com/airbnb/visx/blob/master/packages/visx-xychart/README.md
Demonstrates how to use EventEmitterProvider to emit and subscribe to events within visx components. This is useful for implementing features like linked tooltips or shared data across charts.
```tsx
import React, { useState } from 'react';
import { useEventEmitter, EventEmitterProvider } from '@visx/xychart';
const eventSourceId = 'optional-source-id-filter';
const EmitEvent = () => {
const emit = useEventEmitter();
return (
);
};
const SubscribeToEvent = () => {
const [clickCount, setClickCount] = useState(0);
const allowedEventSources = [eventSourceId];
useEventEmitter('pointerup', () => setClickCount(clickCount + 1), allowedEventSources);
return
Emitted {clickCount} events
;
};
export default function Example() {
return (
);
}
```
--------------------------------
### Create Custom Gradients
Source: https://github.com/airbnb/visx/blob/master/packages/visx-gradient/Readme.md
Define custom linear or radial gradients by specifying start and end colors.
```js
import { LinearGradient, RadialGradient } from '@visx/gradient';
;
;
```
--------------------------------
### Create a Threshold Legend with @visx/legend
Source: https://github.com/airbnb/visx/blob/master/packages/visx-legend/Readme.md
Use LegendThreshold to display a legend based on a threshold scale. Ensure you have @visx/legend and @visx/scale installed.
```javascript
import { LegendThreshold } from '@visx/legend';
import { scaleThreshold } from '@visx/scale';
const threshold = scaleThreshold({
domain: [0.02, 0.04, 0.06, 0.08, 0.1],
range: ['#f2f0f7', '#dadaeb', '#bcbddc', '#9e9ac8', '#756bb1', '#54278f'],
});
function MyChart() {
return (
);
}
```
--------------------------------
### Migrating XYChart Theme to Primitive Theme
Source: https://github.com/airbnb/visx/blob/master/packages/visx-theme/Readme.md
Demonstrates how to adapt an existing `@visx/xychart` theme to be used with new primitive Visx charts using `fromXYChartTheme`.
```tsx
import { XYChart, buildChartTheme } from '@visx/xychart';
import { ThemeScope, fromXYChartTheme } from '@visx/theme';
const legacyTheme = buildChartTheme({
backgroundColor: '#ffffff',
colors: ['#3b82f6', '#10b981', '#f59e0b', '#ef4444', '#8b5cf6'],
gridColor: '#f3f4f6',
gridColorDark: '#e5e7eb',
tickLength: 4,
});
const primitiveTheme = fromXYChartTheme(legacyTheme);
export function Dashboard() {
return (
<>
{/* existing chart */}{/* new primitive chart */}
>
);
}
```
--------------------------------
### Basic Animated Line Chart with Tooltip
Source: https://github.com/airbnb/visx/blob/master/packages/visx-xychart/README.md
Illustrates basic usage for an animated line chart with a bottom Axis, Grid, and Tooltip. Requires importing necessary components from '@visx/xychart'.
```tsx
import {
AnimatedAxis, // any of these can be non-animated equivalents
AnimatedGrid,
AnimatedLineSeries,
XYChart,
Tooltip,
} from '@visx/xychart';
const data1 = [
{ x: '2020-01-01', y: 50 },
{ x: '2020-01-02', y: 10 },
{ x: '2020-01-03', y: 20 },
];
const data2 = [
{ x: '2020-01-01', y: 30 },
{ x: '2020-01-02', y: 40 },
{ x: '2020-01-03', y: 80 },
];
const accessors = {
xAccessor: (d) => d.x,
yAccessor: (d) => d.y,
};
const render = () => (
(
)}
/>
);
```
--------------------------------
### Create linear scales for charts
Source: https://github.com/airbnb/visx/blob/master/packages/visx-scale/Readme.md
Example of using scaleLinear to map data domains to SVG coordinate ranges for a bar chart.
```js
const graphWidth = 500;
const graphHeight = 200;
const [minX, maxX] = getXMinAndMax();
const [minY, maxY] = getYMinAndMax();
const xScale = Scale.scaleLinear({
domain: [minX, maxX], // x-coordinate data values
range: [0, graphWidth], // svg x-coordinates, svg x-coordinates increase left to right
round: true,
});
const yScale = Scale.scaleLinear({
domain: [minY, maxY], // y-coordinate data values
// svg y-coordinates, these increase from top to bottom so we reverse the order
// so that minY in data space maps to graphHeight in svg y-coordinate space
range: [graphHeight, 0],
round: true,
});
// ...
const points = data.map((d, i) => {
const barHeight = graphHeight - yScale(d.y);
return ;
});
```
--------------------------------
### Initialize and use Point
Source: https://github.com/airbnb/visx/blob/master/packages/visx-point/Readme.md
Create a new Point instance and retrieve coordinates as an object or an array.
```javascript
import { Point } from '@visx/point';
const point = new Point({ x: 2, y: 3 });
const { x, y } = point.value(); // Get the coords as an object
const [x, y] = point.toArray(); // or array
```
--------------------------------
### Add @types/react as a dev dependency
Source: https://github.com/airbnb/visx/blob/master/MIGRATION.md
For TypeScript users on React 18 or 19, install @types/react as a development dependency to match your React version.
```bash
yarn add -D @types/react
```
--------------------------------
### Tooltip State Management (Hooks and HOCs)
Source: https://github.com/airbnb/visx/blob/master/packages/visx-tooltip/Readme.md
Overview of the `useTooltip` hook and `withTooltip` HOC for managing tooltip state.
```APIDOC
## Tooltip State Management
This package provides two ways to add tooltip **state** logic to your chart components:
- **`useTooltip()`**: A hook recommended for functional components.
- **`withTooltip()`**: A higher-order component (HOC) suitable for both functional and class components.
Both `useTooltip` and `withTooltip` expose the same values and functions:
| Name | Type | Description |
| :------------ | :----- | :---------------------------------------------------------------------------------------------------------------------------------------------------- |
| showTooltip | func | Call this function with the signature `func({ tooltipData, tooltipLeft, tooltipTop })` to set the tooltip state to the specified values. |
| hideTooltip | func | Call this function to close a tooltip, i.e., set the `showTooltip` state to `false`. |
| tooltipOpen | bool | Whether the tooltip state is open or closed |
| tooltipLeft | number | The `tooltipLeft` position passed to the `showTooltip` func, intended to be used for tooltip positioning |
| tooltipTop | number | The `tooltipTop` position passed to the `showTooltip` func, intended to be used for tooltip positioning |
| tooltipData | any | The `tooltipData` value passed to the `showTooltip` func, intended to be used for any data that your tooltip might need to render |
| updateTooltip | func | Call this function with the signature `func({ tooltipOpen, tooltipLeft, tooltipTop, tooltipData })` to set the tooltip state to the specified values. |
### `useTooltip()`
If you would like to add tooltip state logic to a functional component, you may use the `useTooltip()` hook. **For correct tooltip positioning, it is important to wrap your component in an element (e.g., `div`) with `relative` positioning**.
### `withTooltip(BaseComponent [, containerProps [, renderContainer]])`
If you would like to add tooltip state logic to a class component, you may wrap it in `withTooltip(BaseComponent [, containerProps [, renderContainer])`. The HOC will wrap your component in a `div` with `relative` positioning by default and handle state for tooltip positioning, visibility, and content by injecting the following props into your `BaseComponent`.
```
--------------------------------
### Revenue Scales with useChartDimensions and useScale
Source: https://github.com/airbnb/visx/blob/master/packages/visx-chart/Readme.md
Demonstrates how to use `useChartDimensions` and `useScale` to create band and linear scales for a revenue dataset. `xMax` and `yMax` are aliases for `innerWidth` and `innerHeight`.
```tsx
import { useChartDimensions } from '@visx/chart';
import { useScale } from '@visx/scale/react';
export function useRevenueScales({ data, width, height }) {
const dimensions = useChartDimensions({
width,
height,
margin: { top: 16, right: 16, bottom: 32, left: 48 },
});
const maxRevenue = Math.max(0, ...data.map((datum) => datum.revenue));
const xScale = useScale({
type: 'band',
domain: data.map((datum) => datum.month),
range: [0, dimensions.xMax],
padding: 0.2,
});
const yScale = useScale({
type: 'linear',
domain: [0, maxRevenue],
range: [dimensions.yMax, 0],
nice: true,
});
return { dimensions, xScale, yScale };
}
```
--------------------------------
### Custom Data Accessors and Scale
Source: https://github.com/airbnb/visx/blob/master/packages/visx-heatmap/Readme.md
Define custom accessors (x, y, z) to map your data structure to heatmap properties. Example shows defining an xScale using these accessors.
```javascript
// Example accessors
const x = (d) => d.myBin;
const y = (d) => d.myBins;
const z = (d) => d.myCount;
// Example scale with an accessors
const xScale = scaleLinear({
range: [0, xMax],
domain: extent(data, x),
});
```
--------------------------------
### Line Chart Recipe with Visx Theme Hooks
Source: https://github.com/airbnb/visx/blob/master/packages/visx-theme/Readme.md
Implements a line chart using Visx primitive components and theme hooks for styling axes, grids, and colors.
```tsx
import { AxisBottom } from '@visx/axis';
import { GridRows } from '@visx/grid';
import { LinePath } from '@visx/shape';
import { useAxisStyle, useColor, useGridStyle } from '@visx/theme/react';
export function RevenueLine({ data, xScale, yScale }) {
const axis = useAxisStyle('bottom');
const grid = useGridStyle();
const lineColor = useColor(0);
return (
<>
xScale(datum.date)}
y={(datum) => yScale(datum.revenue)}
stroke={lineColor}
strokeWidth={2}
/>
>
);
}
```
--------------------------------
### Provide ResizeObserver Polyfill
Source: https://github.com/airbnb/visx/blob/master/packages/visx-responsive/Readme.md
If `ResizeObserver` is not available, you can provide a polyfill to `useParentSize`, `ParentSize`, or `withParentSize` to ensure auto-sizing functionality.
```tsx
import { ResizeObserver } from 'your-favorite-polyfill';
// hook
useParentSize({ resizeObserverPolyfill: ResizeObserver });
// component
{() => {...}}
// enhancer
withParentSize(MyComponent, ResizeObserver);
```
--------------------------------
### Update Tooltip Component for nodeRef in @visx/bounds
Source: https://github.com/airbnb/visx/blob/master/MIGRATION.md
When using `withBoundingRects`, ensure the wrapped component accepts and passes the `nodeRef` prop to the measured DOM element. This example shows the TypeScript update for a Tooltip component.
```diff
```diff
- function Tooltip({ rect, parentRect, children }) {
- return
{children}
;
+ type TooltipProps = Omit & {
+ nodeRef?: React.Ref;
+ };
+
+ function Tooltip({ rect, parentRect, nodeRef, children }: TooltipProps) {
+ return
{children}
;
}
```
```
--------------------------------
### Voronoi Diagram Usage with @visx/delaunay
Source: https://github.com/airbnb/visx/blob/master/packages/visx-delaunay/Readme.md
Demonstrates how to use the voronoi layout and Polygon component from @visx/delaunay to render Voronoi regions. Ensure width and height are set for extent, and x/y accessors match your data structure.
```javascript
import { voronoi, Polygon } from '@visx/delaunay';
const points = Array(n).fill(null).map(() => ({
x: Math.random() * innerWidth,
y: Math.random() * innerHeight,
}));
// width + height set an extent on the voronoi
// x + y set relevant accessors depending on the shape of your data
const voronoiDiagram = voronoi({
data: points,
x: d => d.x,
y: d => d.y,
width,
height,
});
const polygons = Array.from(voronoiDiagram.cellPolygons());
return (
)
```
--------------------------------
### Tooltip with Bounding Rects
Source: https://github.com/airbnb/visx/blob/master/packages/visx-bounds/Readme.md
Example of using the `withBoundingRects` HOC to create a Tooltip component that adjusts its position to prevent overflow within its parent container. The HOC passes the element's and its parent's bounding rectangles to the component.
```tsx
import React from 'react';
import { withBoundingRects, WithBoundingRectsProps } from '@visx/bounds';
type TooltipProps = Omit & {
left: number;
top: number;
nodeRef?: React.Ref;
children?: React.ReactNode;
};
function Tooltip({
left: initialLeft,
top: initialTop,
rect,
parentRect,
nodeRef,
children,
}: TooltipProps) {
let left = initialLeft;
let top = initialTop;
if (rect && parentRect) {
left = rect.right > parentRect.right ? left - rect.width : left;
top = rect.bottom > parentRect.bottom ? top - rect.height : top;
}
return (
{children}
);
}
export default withBoundingRects(Tooltip);
```
--------------------------------
### Providing a ResizeObserver Polyfill
Source: https://github.com/airbnb/visx/blob/master/packages/visx-annotation/Readme.md
Illustrates how to provide a ResizeObserver polyfill to the Label component if needed. This is useful for environments that do not natively support ResizeObserver.
```tsx
import { ResizeObserver } from 'your-favorite-polyfill';
function App() {
return
}
```
--------------------------------
### Use React Hook for Chart Accessibility
Source: https://github.com/airbnb/visx/blob/master/packages/visx-a11y/Readme.md
Employ the `useChartA11y` hook from the React entry when chart components require React-bound props and companion components. This example shows integrating ARIA props, a description, a data table, and an announcer into a React component.
```tsx
'use client';
import { useChartA11y } from '@visx/a11y/react';
export function RevenueChart({ data }) {
const a11y = useChartA11y({
id: 'revenue-chart',
title: 'Revenue by month',
chartType: 'line',
data,
x: (datum) => datum.month,
y: (datum) => datum.revenue,
yLabel: 'Revenue',
formatY: (value) => `$${value}`,
});
return (
<>
>
);
}
```
--------------------------------
### Import and Use Mock Data
Source: https://github.com/airbnb/visx/blob/master/packages/visx-mock-data/Readme.md
Import the Mock object or specific datasets like cityTemperature from @visx/mock-data to use in your applications.
```javascript
import Mock from '@visx/mock-data';
// or import { cityTemperature } from '@visx/mock-data';
const data = Mock.cityTemperature;
```
--------------------------------
### Bar Chart Recipe with Visx Theme Hooks
Source: https://github.com/airbnb/visx/blob/master/packages/visx-theme/Readme.md
Constructs a bar chart using Visx primitive components and theme hooks for axis styling and series configuration.
```tsx
import { AxisBottom, AxisLeft } from '@visx/axis';
import { Bar } from '@visx/shape';
import type { ChartConfig } from '@visx/theme';
import { useAxisStyle, useChartConfig } from '@visx/theme/react';
const seriesConfig = {
desktop: { label: 'Desktop' },
mobile: { label: 'Mobile' },
} satisfies ChartConfig<'desktop' | 'mobile'>;
export function TrafficBars({ data, xScale, yScale }) {
const xAxis = useAxisStyle('bottom');
const yAxis = useAxisStyle('left');
const { getColor, getLabel } = useChartConfig(seriesConfig, {
order: ['desktop', 'mobile'],
});
return (
<>
{data.map((datum) => (
))}
>
);
}
```
--------------------------------
### Create a Color Scale
Source: https://github.com/airbnb/visx/blob/master/packages/visx-scale/Readme.md
Initialize a scaleOrdinal using a domain of data and a color scheme from d3-scale-chromatic.
```js
import { scaleOrdinal } from '@visx/scale';
import { schemeSet1 } from 'd3-scale-chromatic';
const colorScale = scaleOrdinal({
domain: arrayOfThings,
range: schemeSet1,
});
```
--------------------------------
### Using @visx/curve functions
Source: https://github.com/airbnb/visx/blob/master/packages/visx-curve/Readme.md
How to import and apply curve functions to visx shape components.
```APIDOC
## Using @visx/curve
### Description
Import curve functions from @visx/curve and pass them to the `curve` prop of visx shape components like `LinePath` to define the interpolation style.
### Usage Example
```javascript
import { curveCatmullRomOpen } from '@visx/curve';
import { LinePath } from '@visx/shape';
const line = ();
```
### Available Curve Functions
- **curveBasis**
- **curveBasisClose**
- **curveBasisOpen**
- **curveStep**
- **curveStepAfter**
- **curveStepBefore**
- **curveBundle**
- **curveLinear**
- **curveLinearClosed**
- **curveMonotoneX**
- **curveMonotoneY**
- **curveCardinal**
- **curveCardinalClosed**
- **curveCardinalOpen**
- **curveCatmullRom**
- **curveCatmullRomClosed**
- **curveCatmullRomOpen**
- **curveNatural**
```