Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the correct type for rechart's Legend content?

In an app I'm helping with there is a render of rechart charts with a legend as follows:

<Legend
  content={renderLegend}
/>

renderLegend is defined as the following function:

const renderLegend = (props) => {
  const { payload } = props;

  return (
    <ul>
      {
        payload.reverse().map((entry, index) => (
          <li key={`item-${index}`}>
            <span style={{backgroundColor: entry.color}} />
            <span>{entry.payload.value}</span>&nbsp;{entry.value}
          </li>
        ))
      }
    </ul>
  );
};

This function suggests that the type for props.payload should be something like:

interface props {
  payload: {
    color: string;
    value: string;
    payload: {
      value: string;
    }
  }[];
}

In TS, I'd like to type the function renderLegend appropriately but this type seemingly does not exist. The property content of the Legend component takes a ContentType which translates to ReactElement | (props: Props) => Element where Props does contain a payload property but if I try and access it I find it doesn't have a value attribute. It's important to mention that this works as is, written in Typescript with no typing. I'm trying to add typing to have better acces to this payload.

like image 885
Ronny Efronny Avatar asked Dec 09 '25 18:12

Ronny Efronny


1 Answers

Recharts provides the type Payload. Try:

interface props {
  payload: Payload[];
}

Don't forget to import if your editor doesn't do so automatically:

import type { Payload } from "recharts/types/component/DefaultLegendContent";

like image 164
megakeegman Avatar answered Dec 12 '25 14:12

megakeegman