UNPKG

react-scroll-into-view

Version:

Simple React element that when clicked scrolls to any element on page

55 lines (53 loc) 1.6 kB
import React from "react"; //#region src/index.tsx const validScrollOptions = (scrollOptions) => { if (typeof scrollOptions !== "object") return {}; return Object.entries(scrollOptions).reduce((acc, [key, val]) => { switch (key) { case "behavior": if (val === "auto" || val === "smooth") acc[key] = val; break; case "block": case "inline": if (val === "start" || val === "center" || val === "end" || val === "nearest") acc[key] = val; break; default: } return acc; }, {}); }; const ScrollInto = ({ children, selector, smooth = true, style = {}, alignToTop = false, className = "", onClick, scrollOptions = {} }) => { const scrollIntoView = () => { const options = { behavior: smooth ? "smooth" : "auto", ...validScrollOptions(scrollOptions) }; if (alignToTop) { options.block = "start"; options.inline = "nearest"; } document.querySelector(selector)?.scrollIntoView(options); }; /** * Click event handler * When provided (optional) `onClick` property which is a function it will call it and wait 16ms (single frame) to use * `scrollIntoView` as e.g. MaterialUI Menu changes `body` element style to `overflow: hidden` blocking * `scrollIntoView` */ const handleClick = (event) => { if (typeof onClick === "function") { onClick(event); setTimeout(scrollIntoView, 1e3 / 60); return; } scrollIntoView(); }; return /* @__PURE__ */ React.createElement("div", { style, className, onClick: handleClick }, children); }; //#endregion export { ScrollInto, ScrollInto as default }; //# sourceMappingURL=index.mjs.map