DEV Community

George Pamfilis
George Pamfilis

Posted on

Handle back-press NextJS navigate to route other than previous - snippet

"use client";
import { Box, styled } from "@mui/material";
import ThankYouRequest from "@/_components/thankyourequest";
import { useRouter } from "next/navigation";
import { useEffect } from "react";

const FOOTER_HEIGHT = 60; // Constant for the footer height
const HEADER_HEIGHT = 80; // Adjust this value to control the header height

const SectionContainer = styled(Box)({
  position: "relative",
  height: `calc(100vh - ${HEADER_HEIGHT}px - ${FOOTER_HEIGHT}px)`,
  display: "flex",
  justifyContent: "center",
  alignItems: "center",
  overflow: "hidden",
});

const useBackButtonDetector = (onBack) => {
  useEffect(() => {
    const handleBackButton = (event) => {
      event.preventDefault();
      onBack(); // Callback function when back button is detected
    };

    window.history.pushState(null, null, window.location.pathname);
    window.addEventListener("popstate", handleBackButton);

    return () => window.removeEventListener("popstate", handleBackButton);
  }, [onBack]);
};

export default function ThankYouPage({
  params,
}: {
  params: { businessName: string; requestID: string };
}) {
  const router = useRouter();

  const handleBack = () => {
    console.log("Back button pressed");
    router.push(`/client/${params.businessName}/book`); // Redirect to the business page
    // Your custom logic here
  };

  useBackButtonDetector(handleBack);

  return (
    <>
      <SectionContainer>
        <ThankYouRequest booking_request_id={params.requestID} />
      </SectionContainer>
    </>
  );
}

Enter fullscreen mode Exit fullscreen mode

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay