---
title: "Context API"
framework: react
version: "14.1.0"
---

# Context API

This section covers how shared contextual information is passed to the chart elements.

## Overview

The purpose of the Context Object is to attach additional information to custom callbacks such as [Formatters](https://www.ag-grid.com/charts/react/formatters/), [Stylers](https://www.ag-grid.com/charts/react/stylers/) and [Tooltip Renderers](https://www.ag-grid.com/charts/react/tooltips/#modifying-content). The Context Object is accessible via the `context` property in all callback and event handler parameters.

## Context Object

The Context Object can be set using the `context` property either at the root of the chart options, or on an individual series or axis. The `series[].context` and `axes[].context` values will be used for callbacks related to the target series or axis, but will fallback to the root `context` property if they are not set.

```js
{
    context: 'my root context',
    series: [
        {
            type: 'bar',
            itemStyler: ({ context }) => {
                console.log(context); // prints 'my root context'
            },
        },
        {
            context: 'my series context',
            type: 'bar',
            itemStyler: ({ context }) => {
                console.log(context); // prints 'my series context'
            },
        },
    ],
    axes: {
        x: {
            type: 'number',
            position: 'bottom',
            label: {
                formatter: ({ context }) => {
                    console.log(context); // prints 'my root context'
                },
            },
        },
        y: {
            type: 'number',
            position: 'left',
            context: 'my axis context',
            label: {
                formatter: ({ context }) => {
                    console.log(context); // prints 'my axis context'
                },
            },
        },
    },
}
```

In this snippet:

- `series[0]` and `axes.x` do not have their own `context` defined, so the callbacks use the `context` defined at the root.
- `series[1]` and `axes.y` have custom `context` values defined, and these will be used in callbacks.

## Context Object Example

The example below shows how the Context Object can be used.

Change the User Currency in the dropdown to update the Context Object state, which updates the tooltip and the axis labels.

#### Currency Converter

```tsx
import React, { useState, Fragment } from "react";
import { createRoot } from "react-dom/client";
import { AgCharts } from "ag-charts-react";
import {
  AgCartesianChartOptions,
  AnimationModule,
  CandlestickSeriesModule,
  ContextMenuModule,
  CrosshairModule,
  LegendModule,
  ModuleRegistry,
  NumberAxisModule,
  TimeAxisModule,
} from "ag-charts-enterprise";
import {
  Currency,
  CurrencyConverter,
  makeCurrencyConverter,
} from "./currencyConverter";
import { TradeDatum, getData } from "./data";
import clone from "clone";

ModuleRegistry.registerModules([
  AnimationModule,
  CandlestickSeriesModule,
  ContextMenuModule,
  CrosshairModule,
  LegendModule,
  NumberAxisModule,
  TimeAxisModule,
]);

const ChartExample = () => {
  const [options, setOptions] = useState<
    AgCartesianChartOptions<TradeDatum, CurrencyConverter>
  >({
    context: makeCurrencyConverter("EUR"),
    title: {
      text: "Stock Prices",
    },
    data: getData(),
    series: [
      {
        type: "candlestick",
        xKey: "date",
        openKey: "open",
        highKey: "high",
        lowKey: "low",
        closeKey: "close",
        tooltip: {
          renderer: ({ datum, context }) => {
            if (context == null) return {};
            return {
              title: datum.date.toDateString(),
              data: [
                {
                  label: "Open",
                  value: context.formatBothCurrencies(datum.open),
                },
                {
                  label: "High",
                  value: context.formatBothCurrencies(datum.high),
                },
                {
                  label: "Low",
                  value: context.formatBothCurrencies(datum.low),
                },
                {
                  label: "Close",
                  value: context.formatBothCurrencies(datum.close),
                },
              ],
            };
          },
        },
      },
    ],
    axes: {
      x: {
        type: "time",
      },
      y: {
        type: "number",
        label: {
          formatter: ({ value, context }) => {
            return context?.formatUserCurrency(value);
          },
        },
      },
    },
    contextMenu: {
      items: [
        {
          showOn: "series-node",
          label: "Log as USD",
          action: ({ datum, context }) =>
            console.log(context?.formatLog(datum, "USD")),
        },
        {
          showOn: "series-node",
          label: "Log as EUR",
          action: ({ datum, context }) =>
            console.log(context?.formatLog(datum, "EUR")),
        },
        {
          showOn: "series-node",
          label: "Log as GBP",
          action: ({ datum, context }) =>
            console.log(context?.formatLog(datum, "GBP")),
        },
        {
          showOn: "series-node",
          label: "Log as JPY",
          action: ({ datum, context }) =>
            console.log(context?.formatLog(datum, "JPY")),
        },
        {
          showOn: "series-node",
          label: "Log as INR",
          action: ({ datum, context }) =>
            console.log(context?.formatLog(datum, "INR")),
        },
      ],
    },
  });

  const onMySelectChange = (value: Currency) => {
    const nextOptions = clone(options);

    nextOptions.context = makeCurrencyConverter(value);

    setOptions(nextOptions);
  };

  return (
    <Fragment>
      <div className="example-controls">
        <div className="controls-row">
          <label htmlFor="mySelect">User Currency: </label>
          <select
            id="mySelect"
            onChange={(event) => onMySelectChange(event.target.value)}
          >
            <option value="EUR">🇪🇺 Euros (€)</option>
            <option value="USD">🇺🇸 US Dollars ($)</option>
            <option value="GBP">🇬🇧 Sterling Pound (£)</option>
            <option value="JPY">🇯🇵 Japanese Yen (¥)</option>
            <option value="INR">🇮🇳 Indian Rupee (₹)</option>
          </select>
        </div>
      </div>
      <AgCharts options={options} />
    </Fragment>
  );
};

const root = createRoot(document.getElementById("root")!);
root.render(<ChartExample />);
```

[Live example: Currency Converter](https://www.ag-grid.com/charts/reactFunctionalTs/context/examples/currency-converter)

Note that the Context Object is used by the following callbacks:

- The Y-axis [Label Formatter](https://www.ag-grid.com/charts/react/axes-labels/#formatter), to convert USD values to the preferred User Currency.
- The [Tooltip Renderer](https://www.ag-grid.com/charts/react/tooltips/#modifying-content), to render both the stock prices in USD and the User Currency (if applicable).
- The [Context Menu Actions](https://www.ag-grid.com/charts/react/context-menu/#custom-actions), to log converted stock prices to the console.
