react-top-bottom-scroll
Version:
**Add a user-friendly scroll-to-top/bottom button to your React applications.**
113 lines (112 loc) • 3.3 kB
JavaScript
import "./index.css";
import e from "react";
const x = ({
bottomRef: n = null,
topRef: l = null,
smooth: t = !0,
upIconColor: a = "white",
downIconColor: u = "white",
upTitleMessage: w = "Scroll to top",
downTitleMessage: m = "Scroll to bottom",
style: E = {},
renderIcon: S = null,
id: s = ""
}) => {
const [c, b] = e.useState(0), [f, T] = e.useState(0), [r, h] = e.useState(null), [y, g] = e.useState(!0), i = {
currentScrollPosition: c,
prevScrollPosition: f,
setScrollDirection: h
}, B = () => {
if (n)
n.current.scrollIntoView({
behavior: t ? "smooth" : "instant",
block: "end",
inline: "nearest"
});
else if (s) {
const o = document.getElementById(s);
d(t, o.offsetTop - 400, "center", i);
} else
d(t, document.body.scrollHeight, "end", i);
}, k = () => {
if (l)
l.current.scrollIntoView({
behavior: t ? "smooth" : "instant",
block: "start",
inline: "nearest"
});
else if (s) {
const o = document.getElementById(s);
d(t, o.offsetTop - 400, "center", i);
} else
d(t, 0, "start", i);
};
e.useEffect(() => {
const o = () => {
const p = window.scrollY || document.documentElement.scrollTop || document.body.scrollTop;
b(p);
const P = document.documentElement.scrollTop || document.body.scrollTop;
v(
c,
f,
h
), !P && !p && h(null), T(c);
const C = window.innerHeight + window.scrollY >= document.documentElement.offsetHeight;
g(!C);
};
return window.addEventListener("scroll", o), () => {
window.removeEventListener("scroll", o);
};
}, [f, c]);
const D = () => {
const o = window.innerHeight + window.scrollY <= document.body.offsetHeight;
g(!o);
};
return e.useEffect(() => {
window.addEventListener("scroll", D);
}, []), /* @__PURE__ */ e.createElement(e.Fragment, null, y && r && /* @__PURE__ */ e.createElement(
"a",
{
to: "#",
id: "scroll_button",
style: {
display: "block",
cursor: "pointer",
backgroundColor: "#663399",
...E
},
onClick: r === "down" ? B : k,
title: r === "down" ? m : w
},
S ? S(r) : /* @__PURE__ */ e.createElement(
"svg",
{
xmlns: "http://www.w3.org/2000/svg",
height: "16",
width: "12",
viewBox: "0 0 384 512",
fill: r === "down" ? u : a,
style: {
transform: r === "down" ? "rotate(0deg)" : "rotate(180deg)",
transition: "all 0.3s ease-in-out"
}
},
/* @__PURE__ */ e.createElement("path", { d: "M169.4 470.6c12.5 12.5 32.8 12.5 45.3 0l160-160c12.5-12.5 12.5-32.8 0-45.3s-32.8-12.5-45.3 0L224 370.8 224 64c0-17.7-14.3-32-32-32s-32 14.3-32 32l0 306.7L54.6 265.4c-12.5-12.5-32.8-12.5-45.3 0s-12.5 32.8 0 45.3l160 160z" })
)
));
}, d = (n = !0, l = 0, t = "start", a) => {
const { currentScrollPosition: u, prevScrollPosition: w, setScrollDirection: m } = a;
window.scrollTo({
top: l,
behavior: n ? "smooth" : "instant",
block: t,
easing: "ease-in-out"
}), v(
u,
w,
m
);
}, v = (n, l, t) => (n > l ? t("down") : n < l && t("up"), null);
export {
x as default
};