burktelefon
burktelefon

Reputation: 1018

Add a vertical line in a react-vis chart where mousepointer is hovered

I'm evaluating react-vis. Let's say I have a react-vis simple chart, how would you add a vertical line that moves with the mouse when the chart is hovered? My guess is that I need to add a crosshair component inside the XYPlot, and maybe a YAxis component. But I don't understand how, and I cant't find any releant examples.

function Chart({data}) {
  return <XYPlot width={400} height={300}><XAxis/><YAxis/>
    <HorizontalGridLines />
    <VerticalGridLines />
    <LineMarkSeries data={data} />
    </XYPlot>;
}

Upvotes: 5

Views: 2078

Answers (1)

technogeek1995
technogeek1995

Reputation: 3444

It's possible to add a vertical line with a <Crosshair /> component. You can use this example in the documentation located here. You need to set onMouseLeave and onNearestX handlers to update the Crosshairs line's value. The trick is that you have to put divs inside the Crosshair component so it won't render the value box. I'm using React Hooks to answer your question, but you could have used state with a class (React Hooks State Docs).

import React, { useState } from 'react';

function Chart({data}) {
  const [points, setPoints] = useState([]);

  return <XYPlot
    width={400}
    height={300}
    onMouseLeave={() => setPoints([])}
    >
    <XAxis/>
    <YAxis/>
    <HorizontalGridLines />
    <VerticalGridLines />
    <LineMarkSeries
      data={data}
      onNearestX={v => setPoint([v])}
    />
    <Crosshair values={point}>
      {/* Divs inside Crosshair Component required to prevent value box render */}
      <div></div>
    </Crosshair>
  </XYPlot>;
}

Upvotes: 2

Related Questions