6

I'm using a Biaxial Line Chart, and I'm trying to figure out how to format the content of the Tooltip using the formatter function.

What I want is for my output to read:

2019-01-13
Price: $17.99
Sales Rank: 326,518

I'm currently using the below code which formats the price into a price, but it does not change the sales rank value. I'm also not sure on how to change the labels?

<Tooltip formatter={(value, name) => (name === "price") ? `$${value/100}` : value.toLocaleString()}/>

enter image description here

K20GH
  • 6,032
  • 20
  • 78
  • 118

3 Answers3

2

If you want to format the label in particular, you can use labelFormatter instead of formatter:

<Tooltip
  labelFormatter={value => {
    return `label: ${value}`;
  }} 
/>
Ofelia Muradova
  • 127
  • 3
  • 17
  • this would change the date in his case, wouldn't it? Not the price & sales_rank – trainoasis May 11 '22 at 16:40
  • @trainoasis yes, in case everything needs formatting I would use a Custom Tooltip. In case it just the label (in this question - date), labelFormatter works just fine – Ofelia Muradova May 13 '22 at 10:21
0

As soon as formatter accepts also props, you can try to alter that object. Props has all the data displayed in a tooltip.

const formatter = (value, name, props) => {
    console.log("V", value, "N", name, "P", props); // for debug
    props.payload = Object.keys(props.payload).map(k => {
        return props.payload[k] = isNaN(props.payload[k]) ? props.payload[k] : format(props.payload[k]);
    })
    return [value, name, props]
}

Though I'm not sure this is a good solution, because for me it sometimes breaks chart on resize. But maybe you can make it work.

Daniel Titkov
  • 922
  • 1
  • 9
  • 14
0

You can create CustomTooltip Component that can display the data as per your requirement as done below

  const CustomTooltip = ({ active, payload, label }) => {
    console.log("payload",payload);  //you check payload
    if (active) {
      return (
        <div>
         <Card>
          <p>{date} </p>
          <p>Price : ${}</p>
          <p>Sales Rank :${} </p>
          <Card>
        </div>
      );
    }

    return null;
  };

payload array image payload variable contain all axis values and data as per your requirement for example

where payload[0] contain x-axis and payload1 contain y-axis and payload[2] contain z-axis as per your requirement you can extract value from array

       <div>
          <p>{date} </p>
          <p>Price : ${payload[0].data}</p>
          <p>Sales Rank :${payload[1].data} </p>
        </div>

and date can we extract from the payload[0].payload which contains entire object of the data that you pass in chart and you can pass your CustomTooltip in Tooltip as below shown

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

Whenever you cursor over points on graph can able to see the tooltips as you wish