Search code examples
reactjsrecharts

View chart cursor only in the chart's portion in areachart of Recharts


I am trying to use rechart's areachart. There is an option to enable cursor which will show the points plotted on the graph on hover. However I want to show that cursor only uptill where the chart's portion lies and not above that. Is there anyway to achieve this?

Want to achieve this


Solution

  • I was able to achieve this by using a custom component for cursor. First, I had to store the position of the active dot in a state variable and then pass this variable as a prop to custom cursor component and then draw the line uptil the active dot.

    const CustomCursor = (props) => {
      const { points, activeDotPos } = props;
    
      const startingPoint = points[0];
      const endingPoint = points[1];
    
      const [x1, y1] = [startingPoint.x, activeDotPos.y + 10]; // adding 10 to y to prevent cursor from overlapping with active dot
      const [x2, y2] = [endingPoint.x, endingPoint.y];
    
      return (
        <svg x1={x1} y1={y1} x2={x2} y2={y2}>
          <line
            x1={x1}
            y1={y1}
            x2={x2}
            y2={y2}
            stroke={"#B5B5B5"}
            strokeWidth={1}
            strokeDasharray={"10 10"}
          />
        </svg>
      );
    };
    

    Example Sandbox