Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript Interface for Recharts Custom Tooltip

Being not well-versed with Typescript yet, I am trying to create a custom Tooltip content for my Recharts chart in my React app with Typescript. @types/recharts has already been installed as one of the a devDependencies.

However, when I define the CustomTooltip function as shown below, Typescript is throwing an error

Binding element 'active' implicitly has an 'any' type. TS7031

How can we solve this issue?

const CustomTooltip = ({ active, payload, label }) => {
    if (active) {
        return (
        <div className="custom-tooltip">
            <p className="label">{`${label} : ${payload[0].value}`}</p>
            <p className="desc">Anything you want can be displayed here.</p>
        </div>
        );
    }

    return null;
}

return (
    <ComposedChart data={data}>
        ...
        <Tooltip content={<CustomTooltip />} />
    </ComposedChart>
)

Tried defining an interface, but got another error

Type '{}' is missing the following properties from type 'ICustomToolip': active, payload, label TS2739

interface ICustomToolip {
    active: any;
    payload: any;
    label: any;
}

const CustomTooltip = ({ active, payload, label }: ICustomToolip) => {
    if (active) {
        return (
        <div className="custom-tooltip">
            <p className="label">{`${label} : ${payload[0].value}`}</p>
            <p className="desc">Anything you want can be displayed here.</p>
        </div>
        );
    }

    return null;
}
like image 358
Athena Wisdom Avatar asked Sep 14 '25 07:09

Athena Wisdom


2 Answers

Try to do the following (using rechart's types).

import { TooltipProps } from 'recharts';
// for recharts v2.1 and above
import {
    ValueType,
    NameType,
} from 'recharts/types/component/DefaultTooltipContent';
// for recharts versions below v2.1
import {
    ValueType,
    NameType,
} from 'recharts/src/component/DefaultTooltipContent';

const CustomTooltip = ({
    active,
    payload,
    label,
}: TooltipProps<ValueType, NameType>) => {
    if (active) {
    return (
        <div className="custom-tooltip">
        <p className="label">{`${label} : ${payload?.[0].value}`}</p>
        <p className="desc">Anything you want can be displayed here.</p>
        </div>
    );
    }

    return null;
};

return (
    <ComposedChart data={data}>
    ...
    <Tooltip content={<CustomTooltip />} />
    </ComposedChart>
);
like image 161
Daria Babakova Avatar answered Sep 15 '25 21:09

Daria Babakova


Use:

const CustomTooltip = ({ active, payload, label }: TooltipProps<number, string>): JSX.Element => {

Change number and string to your data types. You can also use it with the ValueType and NameType, but it makes more sense to declare it with your types.

const CustomTooltip = ({ active, payload, label }: TooltipProps<ValueType, NameType>): JSX.Element => {
like image 30
Tob Avatar answered Sep 15 '25 19:09

Tob