diff --git a/src/components/button/useButtonClick.ts b/src/components/button/useButtonClick.ts index 2d2b89b..88ce15b 100644 --- a/src/components/button/useButtonClick.ts +++ b/src/components/button/useButtonClick.ts @@ -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) => { + const handleClick = React.useCallback( + (event: React.MouseEvent) => { 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; };