Recharts - Tooltip Formatter on Biaxial Line Charts?

Viewed 3860

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

3 Answers

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

<Tooltip
  labelFormatter={value => {
    return `label: ${value}`;
  }} 
/>

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.

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

Related