fix(nav): handle navigation from other pages in SmoothLink
This commit is contained in:
@@ -1,5 +1,6 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
|
import { usePathname, useRouter } from "next/navigation";
|
||||||
import { ReactNode } from "react";
|
import { ReactNode } from "react";
|
||||||
|
|
||||||
interface SmoothLinkProps {
|
interface SmoothLinkProps {
|
||||||
@@ -15,22 +16,49 @@ export default function SmoothLink({
|
|||||||
className,
|
className,
|
||||||
onClick,
|
onClick,
|
||||||
}: SmoothLinkProps) {
|
}: SmoothLinkProps) {
|
||||||
|
const pathname = usePathname();
|
||||||
|
const router = useRouter();
|
||||||
|
|
||||||
const handleClick = (e: React.MouseEvent<HTMLAnchorElement>) => {
|
const handleClick = (e: React.MouseEvent<HTMLAnchorElement>) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
|
|
||||||
const targetId = href.replace("#", "");
|
// Si on clique sur "/" (Accueil)
|
||||||
const element = document.getElementById(targetId);
|
if (href === "/") {
|
||||||
|
if (pathname === "/") {
|
||||||
|
// On est déjà sur l'accueil, scroll vers le haut
|
||||||
|
window.scrollTo({ top: 0, behavior: "smooth" });
|
||||||
|
} else {
|
||||||
|
// On est sur une autre page, naviguer vers l'accueil
|
||||||
|
router.push("/");
|
||||||
|
}
|
||||||
|
onClick?.();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Si c'est une ancre (#section)
|
||||||
|
if (href.startsWith("#")) {
|
||||||
|
const targetId = href.replace("#", "");
|
||||||
|
|
||||||
|
if (pathname === "/") {
|
||||||
|
// On est sur l'accueil, smooth scroll vers la section
|
||||||
|
const element = document.getElementById(targetId);
|
||||||
if (element) {
|
if (element) {
|
||||||
element.scrollIntoView({
|
element.scrollIntoView({
|
||||||
behavior: "smooth",
|
behavior: "smooth",
|
||||||
block: "start",
|
block: "start",
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
if (onClick) {
|
// On est sur une autre page, naviguer vers l'accueil + ancre
|
||||||
onClick();
|
router.push(`/${href}`);
|
||||||
}
|
}
|
||||||
|
onClick?.();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sinon, navigation normale
|
||||||
|
router.push(href);
|
||||||
|
onClick?.();
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
|||||||
Reference in New Issue
Block a user