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

gpamfilis

George Pamfilis

Posted on March 20, 2024

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
💖 💪 🙅 🚩
gpamfilis
George Pamfilis

Posted on March 20, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related