Composables
useScrollToElement
Description
The useScrollToElement composable provides a smooth scroll utility for navigating to specific elements within the DOM. It accounts for responsive header height differences between mobile and desktop views and allows optional customization via scroll options.
FEATURE GOALS
- Enable smooth scrolling to a target DOM element.
- Account for different header heights depending on the device type.
- Support customizable scroll options via native scrollTo() behavior.
FEATURE EXPECTATIONS
- Automatically calculates offset based on device type (mobile or desktop).
- Smooth scrolls to the element’s top position with optional override settings.
- Compatible with server-side rendering (no execution on SSR).
DEV STRATEGIES
- Composables Logic
const element = document.getElementById("contact-section");
if (element) {
useScrollToElement(element, { behavior: "smooth" });
}
- Scrolls to the element while offsetting for fixed headers (desktop only).
- Supports passing in native ScrollToOptions.
- Implementation
export const useScrollToElement = (element: HTMLElement, opts: object = {}) => {
const { isMobile } = useDevice();
const HEADER_HEIGHT = isMobile ? 0 : 124;
window.scrollTo({
top: element.offsetTop - HEADER_HEIGHT,
behavior: "smooth",
...opts,
});
};
- Uses useDevice() to determine if the user is on a mobile device.
- Applies conditional header offset logic before triggering scroll.
- DEFAULT BEHAVIOR
| Feature | Default | Description |
|---|---|---|
HEADER_HEIGHT | 0 (mobile) / 124 (desktop) | Used to offset scroll position based on screen type. |
behavior | smooth | Applies smooth scrolling unless overridden. |
opts | {} | Applies smooth scrolling unless overridden. |
FLOW SUMMARY
- Detects device type using useDevice().
- Calculates an appropriate scroll offset by subtracting the header height.
- Performs a smooth scroll to the element using window.scrollTo(), merged with any passed options.