Search code examples
reactjstypescriptrecharts

How to set Recharts custom tooltip additional argument (React, typescript)


I'm trying to use recharts custom tooltip with additional argument. But when I change from js to typescript, I got an error.

define function

import { TooltipProps } from "recharts";
import { ValueType,
  NameType,
} from "recharts/types/component/DefaultTooltipContent";

const CustomTooltip = (
    { active, payload, label }: TooltipProps<ValueType, NameType>,
    { StackedBarChartLabel }: { StackedBarChartLabel: BarChartShareLabelState }
  ) => {
    if (active && payload && payload.length) {
      return (
        <div style={{ backgroundColor: "white" }}>
          <p>{label}</p>
          {payload.map((pld: any) => (
            <p key={pld.dataKey}>
              {pld.dataKey}:{StackedBarChartLabel[`${label}`][`${pld.dataKey}`]}
            </p>
          ))}
        </div>
      );
    }
    return null;
  };

call function

<Tooltip
  content={(props) => (
    <CustomTooltip
       {...(props as TooltipProps<ValueType, NameType>)}
       StackedBarChartLabel={dataset.StackedBarChartLabel}
   />
   )}
/>

error message

Property 'StackedBarChartLabel' does not exist on type 'IntrinsicAttributes & Props<ValueType, NameType> & { accessibilityLayer?: boolean; active?: boolean; includeHidden?: boolean; ... 17 more ...; wrapperStyle?: CSSProperties; }'.

I excepted that component doesn't recognize TooltipProps type.

Thanks


Solution

  • I found a solution.

    Overloading types and defining functions.

    type MyTooltipState = TooltipProps<ValueType, NameType> & {
         StackedBarChartLabel: BarChartShareLabelState;};
    
    const CustomTooltip = ({
        active,
        payload,
        label,
        StackedBarChartLabel,
    }: MyTooltipState) => {
      if (active && payload && payload.length) {
        return (
          <div style={{ backgroundColor: "white" }}>
            <p>{label}</p>
              {payload.map((pld: any) => (
            <p key={pld.dataKey}>
              {pld.dataKey}:{StackedBarChartLabel[`${label}`][`${pld.dataKey}`]}
            </p>
       ))}
    </div>);}
    return null;};
    

    Call the function as follows.

    <Tooltip
        content={(props) => (
        <CustomTooltip
           active={props.active}
           payload={props.payload}
           label={props.label}
          StackedBarChartLabel={dataset.StackedBarChartLabel}
        />)}
     />