Add JumpToTop component for mobile devices

This commit is contained in:
dertyp7
2024-01-14 18:10:04 +01:00
parent df0168b6bd
commit 357d49a3b1
4 changed files with 83 additions and 4 deletions

View File

@@ -7,6 +7,15 @@ import Skills from "@sections/Skills";
import Projects from "@sections/Projects";
import SectionLine from "@components/SectionLine";
import Footer from "@components/Footer";
import JumpToTop from "@components/JumpToTop";
function isMobileDevice() {
return (
/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(
navigator.userAgent
) || window.innerWidth < 768
);
}
export default function App() {
const aboutRef = useRef(null);
@@ -32,6 +41,11 @@ export default function App() {
}, []);
useEffect(() => {
if (isMobileDevice()) {
// Don't set up the Intersection Observer on small viewports
return;
}
const observer = new IntersectionObserver(
(entries) => {
entries.forEach((entry) => {
@@ -92,7 +106,12 @@ export default function App() {
</div>
<Footer />
<SectionScroll sections={["", "skills", "projects"]} />
{isMobileDevice() ? (
<JumpToTop />
) : (
<SectionScroll sections={["", "skills", "projects"]} />
)}
</div>
);
}

View File

@@ -0,0 +1,51 @@
import { useState, useEffect } from "react";
import "@styles/JumpToTop.scss"; // Assuming you have a CSS file for styling
export default function JumpToTop() {
const [isVisible, setIsVisible] = useState(false);
// Show button when page is scrolled upto given distance
const toggleVisibility = () => {
if (window.scrollY > 50) {
setIsVisible(true);
} else {
setIsVisible(false);
}
};
// Set the top coordinate to 0
// make scrolling smooth
const scrollToTop = () => {
window.scrollTo({
top: 0,
});
};
useEffect(() => {
window.addEventListener("scroll", toggleVisibility);
return () => window.removeEventListener("scroll", toggleVisibility);
}, []);
return (
<div className="jumpToTop">
{isVisible && (
<div onClick={scrollToTop}>
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
className="feather feather-arrow-up-circle"
>
<circle cx="12" cy="12" r="10"></circle>
<polyline points="16 12 12 8 8 12"></polyline>
<line x1="12" y1="16" x2="12" y2="8"></line>
</svg>
</div>
)}
</div>
);
}

11
src/styles/JumpToTop.scss Normal file
View File

@@ -0,0 +1,11 @@
.jumpToTop {
position: fixed;
bottom: 20px;
right: 20px;
cursor: pointer;
svg {
width: 50px;
height: 50px;
}
}

View File

@@ -27,9 +27,7 @@
}
html {
@media (min-width: 768px) {
scroll-behavior: smooth;
}
scroll-behavior: smooth;
}
h1 {