Shruthi R
Shruthi R

Reputation: 1923

How to customise the tooltip data in react 'recharts'?

In React application (using Next.js), I am trying to implement graph feature using recharts http://recharts.org/en-US/api/LineChart. Right now I am trying to display the date and price value in tooltip, price is displaying properly but date is static for all dots(on hover)

My code is like

/index.js

const formatDate = (value) => {
  return moment(value).format('HH:MM A DD MM, YYYY')
}

const weeklyData = [
 { date: formatDate(1613619000), price: '1200.00' },
 { date: formatDate(1613617200), price: '1300.83' },
 { date: formatDate(1613615400), price: '1250.23' },
 { date: formatDate(1613611800), price: '500.55' },
 { date: formatDate(1613608200), price: '1600.23' },
 { date: formatDate(1613606400), price: '1850.93' },
 { date: formatDate(1613604600), price: '1750.23' },
 { date: formatDate(1613599200), price: '650.23' },
]

<LineChart
      width={900}
      height={250}
      data={data}
      margin={{
        top: 5,
        right: 30,
        left: 20,
        bottom: 5,
      }}
    >
      <Tooltip content={<CustomTooltip />} cursor={false} />
      <Line type="monotone" dataKey="price" stroke="#4ec6f4" label="Shruthi" />
</LineChart>

/tooltip.js

const CustomTooltip = ({ active, payload, label }) => {
  if (active && payload && payload.length) {
    return (
      <div className="tooltip">
       <p className="tooltipLabel">{`$${payload[0].payload?.price}`}</p>
       <p className="tooltipDesc">{`${payload[0]?.payload?.date}`}</p>
      </div>
    )
   }

  return null
}

CustomTooltip.propTypes = {
  type: PropTypes.string,
  payload: PropTypes.array,
  label: PropTypes.string,
}

export default CustomTooltip

How can I customise this graph as per my requirement?

Upvotes: 1

Views: 7035

Answers (1)

juliomalves
juliomalves

Reputation: 50268

The issue isn't related to recharts but with moment.js.

Using moment(value) expects the value to be in milliseconds since the Unix Epoch, but in this case the value you are passing represents seconds. Instead, you can use moment.unix(value) which accepts seconds as intended.

const formatDate = (value) => {
    return moment.unix(value).format('HH:MM A DD MM, YYYY')
}

Alternatively, you can still use moment() but then you'll have multiply the value you're passing by 1000 so you get milliseconds instead.

const formatDate = (value) => {
    return moment(value * 1000).format('HH:MM A DD MM, YYYY')
}

Upvotes: 1

Related Questions