34 lines
1.6 KiB
TypeScript
34 lines
1.6 KiB
TypeScript
"use client";
|
|
|
|
import { useCallback } from "react";
|
|
// No import for 'lenis' or 'lenis/react'
|
|
|
|
/**
|
|
* 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).
|
|
}, []);
|
|
|
|
return { handleButtonClick };
|
|
}
|