Update src/components/button/useButtonClick.ts

This commit is contained in:
2026-03-25 23:36:52 +00:00
parent c0c6b67710
commit 99daeff82c

View File

@@ -1,58 +1,54 @@
import { useRouter } from "next/navigation";
import React from "react";
export const useButtonClick = () => {
export const useButtonClick = (
href?: string,
onClickProp?: () => void,
newTab?: boolean
) => {
const router = useRouter();
const handleClick = (
href?: string,
onClick?: () => void,
newTab?: boolean
) => {
return (event: React.MouseEvent<HTMLButtonElement | HTMLAnchorElement>) => {
const handleClick = React.useCallback(
(event: React.MouseEvent<HTMLButtonElement | HTMLAnchorElement>) => {
if (href) {
// Prevent default behavior if an href is provided, as we will handle navigation manually
// This is crucial for hash links and internal Next.js navigation
event.preventDefault();
}
if (onClick) {
onClick();
if (onClickProp) {
onClickProp();
}
if (href) {
if (href.startsWith("http") || href.startsWith("mailto:") || href.startsWith("tel:")) {
// External link, mailto, or tel
if (newTab) {
window.open(href, "_blank", "noopener,noreferrer");
} else {
window.location.href = href;
}
} else if (href.startsWith("#")) {
// Scroll to section for hash links
const targetId = href.substring(1);
// Use getElementById for robust targeting of elements by ID
const targetElement = document.getElementById(targetId);
if (targetElement) {
targetElement.scrollIntoView({
behavior: "smooth"});
// Optionally update URL hash without a full page reload for better UX
behavior: "smooth"
});
window.history.pushState(null, "", href);
} else if (targetId === '') {
// Handle `href="#"` to scroll to top (or do nothing if preferred for placeholder)
window.scrollTo({
top: 0,
behavior: "smooth"});
window.history.pushState(null, '', '/'); // Clear hash
behavior: "smooth"
});
window.history.pushState(null, '', '/');
} else {
console.warn(`Element with ID "${targetId}" not found for smooth scroll.`);
}
} else {
// Internal page navigation using Next.js router
router.push(href);
}
}
};
};
},
[router, href, onClickProp, newTab]
);
return handleClick;
};