skip to Main Content

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

2

Answers


  1. Chosen as BEST ANSWER

    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}
        />)}
     />
    

  2. you can also use code like this in ResponsiveContainer :

    <Tooltip content={<CustomTooltip />} />
    

    you do not need to pass call function which you are being called.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search