Update src/components/button/useButtonClick.ts

This commit is contained in:
2026-03-25 23:39:02 +00:00
parent b76d1546b5
commit 68e5f92dde

View File

@@ -1,54 +1,33 @@
import { useRouter } from "next/navigation";
import React from "react";
"use client";
export const useButtonClick = (
href?: string,
onClickProp?: () => void,
newTab?: boolean
) => {
const router = useRouter();
import { useCallback } from "react";
// No import for 'lenis' or 'lenis/react'
const handleClick = React.useCallback(
(event: React.MouseEvent<HTMLButtonElement | HTMLAnchorElement>) => {
if (href) {
event.preventDefault();
/**
* A hook to provide a consistent click handler for buttons, especially for internal hash navigation.
* It ensures smooth scrolling without relying on external libraries like Lenis or problematic querySelector patterns.
*/
export function useButtonClick() {
const handleButtonClick = useCallback((event: React.MouseEvent<HTMLButtonElement | HTMLAnchorElement>, href?: string) => {
if (href && href.startsWith("#")) {
const id = href.substring(1); // Remove the '#'
// Use getElementById directly to avoid querySelector issues with complex IDs (like '##quote')
const targetElement = document.getElementById(id);
if (targetElement) {
event.preventDefault(); // Prevent default browser jump
targetElement.scrollIntoView({ behavior: "smooth" });
// Optionally update the URL hash without a full page reload or additional scroll
// history.pushState(null, '', href);
} else {
console.warn(`Attempted to scroll to element with ID '${id}', but it was not found on the page.`);
// If the element is not found, we let the default behavior happen (which might lead to a page refresh to the root)
// or prevent it and do nothing. Given it's a "fix" for a bug, a silent failure with a console warning is safer than unexpected navigation.
}
}
// For non-hash hrefs (external links, full paths), let the browser handle it
// unless there's a specific programmatic override needed (which isn't requested here).
}, []);
if (onClickProp) {
onClickProp();
}
if (href) {
if (href.startsWith("http") || href.startsWith("mailto:") || href.startsWith("tel:")) {
if (newTab) {
window.open(href, "_blank", "noopener,noreferrer");
} else {
window.location.href = href;
}
} else if (href.startsWith("#")) {
const targetId = href.substring(1);
const targetElement = document.getElementById(targetId);
if (targetElement) {
targetElement.scrollIntoView({
behavior: "smooth"
});
window.history.pushState(null, "", href);
} else if (targetId === '') {
window.scrollTo({
top: 0,
behavior: "smooth"
});
window.history.pushState(null, '', '/');
} else {
console.warn(`Element with ID "${targetId}" not found for smooth scroll.`);
}
} else {
router.push(href);
}
}
},
[router, href, onClickProp, newTab]
);
return handleClick;
};
return { handleButtonClick };
}