recharts#ReferenceArea TypeScript Examples

The following examples show how to use recharts#ReferenceArea. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: zoom.tsx    From backstage with Apache License 2.0 4 votes vote down vote up
export function useZoomArea() {
  const [showSelection, setShowSelection] = useState(false);
  const [state, setState] = useState<ZoomState>({});
  const { setSelectState, setZoomState, registerSelection } =
    useContext(context);

  const onMouseDown = useCallback(
    (e: any) => {
      if (!e?.activeLabel) return;

      setSelectState({ left: e.activeLabel });
      setShowSelection(true);
    },
    [setSelectState, setShowSelection],
  );

  const onMouseMove = useCallback(
    (e: any) => {
      if (!e?.activeLabel) return;

      setSelectState(area => {
        if (!area.left) {
          return area;
        }
        return { ...area, right: e.activeLabel };
      });
    },
    [setSelectState],
  );

  const doZoom = useCallback(() => {
    setSelectState(old => {
      const { left, right } = old;

      if (left === undefined || right === undefined || left === right) {
        // Either is undefined or both are same - zoom out
        setZoomState({});
      } else if (left < right) {
        setZoomState({ left, right });
      } else if (left > right) {
        setZoomState({ left: right, right: left });
      }

      return {};
    });
    setShowSelection(false);
  }, [setSelectState, setZoomState, setShowSelection]);

  const zoomProps = useMemo(
    () => ({
      onMouseDown,
      onMouseMove,
      onMouseUp: doZoom,
    }),
    [onMouseDown, onMouseMove, doZoom],
  );

  useEffect(() => {
    if (!showSelection) {
      return undefined;
    }
    return registerSelection(setState);
  }, [registerSelection, setState, showSelection]);

  const getZoomArea = useCallback(
    (props?: ZoomAreaProps) => (
      <Fragment key="zoom-area">
        {showSelection && state.left && state.right ? (
          <ReferenceArea
            x1={state.left}
            x2={state.right}
            strokeOpacity={0.5}
            {...props}
          />
        ) : null}
      </Fragment>
    ),
    [showSelection, state.left, state.right],
  );

  return {
    zoomProps,
    getZoomArea,
  };
}