Search code examples
reactjsrecharts

Recharts custom reference line when hovering axis


I'm using Recharts lib, and I need to create this effect on the hovered X Axis:

enter image description here

but I only get neither the gray background or the dotted line, because the only way to do it is within the Tooltip's cursor prop:

enter image description here enter image description here

<Tooltip
    //only BG:
    cursor={{ stroke: "#5C5C5C", opacity: 0.1, strokeWidth: 22 }}
    //only dotted line:
    cursor={{ strokeDasharray: "2 2", strokeWidth: "1", stroke: "#000" }}
  />

Any idea if it's possible? i made a codesandbox for this


Solution

  • You can create a CustomizedCursor that shows both a svg rect and a line. An example implementation could be:

    const CustomCursor = (o: any) => {
      const point0 = o.points[0];
      if (!point0) {
        return null;
      }
      const options = Object.assign(
        {
          width: 0,
          fill: "#fff",
          opacity: 1,
          stroke: "#000",
          strokeWidth: 2,
          strokeDasharray: [4, 2]
        },
        o.options
      );
      return (
        <svg>
          <rect
            x={point0.x - options.width / 2}
            y={o.top}
            width={options.width}
            height={o.height}
            fill={o.options.fill}
            opacity={o.options.opacity}
          />
          <line
            x1={point0.x}
            y1={o.top}
            x2={point0.x}
            y2={o.top + o.height}
            stroke={o.options.stroke}
            strokeWidth={o.options.strokeWidth}
            strokeDasharray={o.options.strokeDasharray}
          />
        </svg>
      );
    };
    

    You can use it to send both types of options (that is for both the rect and the line):

    <Tooltip
      cursor={
         <CustomCursor
            options={{
              stroke: "#000",
              strokeDasharray: [2, 2],
              strokeWidth: 1,
              width: 22,
              opacity: 0.1,
              fill: "#5C5C5C"
            }}
          />
        }
    />
    

    Full code in codesandbox fork