vbotio
vbotio

Reputation: 1684

Rechart legend mismatch formated datakey

I am using Recharts to build a graph with the following data:

id: "mock-device"
props:
  battery: 2,
  cpuUsage: 11,
  diskUsage: 23,
  memoryUsage: 8,
timestamp: 1548031944

and I am building my graph

<AreaChart data={DataGraphs} margin={{ top: 0, right: 0, bottom: 0, left: -30 }}>
  <CartesianGrid strokeDasharray="3 3" />
  <XAxis dataKey="timestamp" tickFormatter={e => (new Date(e * 100).toLocaleTimeString())} />
  <YAxis />
  <Tooltip />
  <Legend />
  <Area dataKey={battery} stroke="#f3a000" fill="#ffc658" />
  <Area dataKey={cpu} stroke="#e4002b" fill="#ff0131a3" />
  <Area dataKey={memory} stroke="#0ea800" fill="#0ea8008c" />
  <Area dataKey={diskUsage} stroke="#009cff" fill="#5abefd" />
</AreaChart>

The problem occurs when the tooltip is displayed, as we can see the title mismatch the tick formatter

enter image description here

So, how can I make both match as they are basically the same information ?

Upvotes: 0

Views: 1375

Answers (1)

Alex Wurts
Alex Wurts

Reputation: 26

You can create a custom tooltip that replaces the one default one. Here is an example of the how you could set a custom tooltip.

<AreaChart width={width} height={height} data={this.data}>
    <Tooltip content={<CustomTooltip />} />
  // Rest of graph configuration here
</AreaChart>);

Here is an example custom tool tip.

import React, { Component } from 'react';
class CustomTooltip extends Component {
    constructor(props) {
        super(props);
    }

    render() {
        var { active } = this.props;
        if (active) {
            const { payload, label } = this.props;
            return (
                <div>
                    <div>{payload[0].value + ' ft'}</div>
                    <div>{label + ' mi'} </div>
                </div>
            );
        }
        return null;
    }
}
export default CustomTooltip;

Payload contains the various values. For you it would be the value for battery, cpu, and etc. Label is the time stamp which you can convert into a more readable text using the same method you used for the tick axis labels.

Upvotes: 1

Related Questions