Ronny Efronny
Ronny Efronny

Reputation: 1538

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.

Upvotes: 3

Views: 2387

Answers (1)

megakeegman
megakeegman

Reputation: 194

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";

Upvotes: 2

Related Questions