5

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>;
}
technogeek1995
  • 3,185
  • 2
  • 31
  • 52
burktelefon
  • 988
  • 2
  • 8
  • 27

1 Answers1

2

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>;
}
technogeek1995
  • 3,185
  • 2
  • 31
  • 52