Skip to content

Commit

Permalink
feat: add scroll to top button
Browse files Browse the repository at this point in the history
  • Loading branch information
Rei-x committed Feb 10, 2023
1 parent 357991c commit 8961cf3
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 7 deletions.
25 changes: 18 additions & 7 deletions src/components/Layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import React from "react";
import { Lato } from "@next/font/google";
import { Footer } from "./Footer";
import { Navbar } from "./Navbar";
import { motion } from "framer-motion";
import { ScrollToTop } from "./ScrollToTop";

const lato = Lato({
subsets: ["latin"],
Expand All @@ -14,12 +16,21 @@ const lato = Lato({

export const Layout = ({ children }: { children: ReactNode }) => {
return (
<Stack minH="100vh" justify="space-between" className={`${lato.variable}`}>
<div>
<Navbar />
<chakra.main>{children}</chakra.main>
</div>
<Footer />
</Stack>
<motion.div>
<Stack
minH="100vh"
as={motion.div}
style={{ overflow: "scroll" }}
justify="space-between"
className={`${lato.variable}`}
>
<div>
<Navbar />
<chakra.main>{children}</chakra.main>
<ScrollToTop />
</div>
<Footer />
</Stack>
</motion.div>
);
};
45 changes: 45 additions & 0 deletions src/components/ScrollToTop.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import { ArrowUpIcon } from "@chakra-ui/icons";
import { Box, IconButton } from "@chakra-ui/react";
import { motion } from "framer-motion";
import React, { useEffect, useState } from "react";
import { AnimatePresenceSSR } from "./AnimatePresenceSSR";

export const ScrollToTop = () => {
const [scrollPosition, setScrollPosition] = useState(0);
const handleScroll = () => {
const position = window.pageYOffset;
setScrollPosition(position);
};

useEffect(() => {
window.addEventListener("scroll", handleScroll, { passive: true });

return () => {
window.removeEventListener("scroll", handleScroll);
};
}, []);
return (
<AnimatePresenceSSR>
{scrollPosition > 500 ? (
<Box position="fixed" bottom="20px" right={["16px", "84px"]} zIndex={1}>
<motion.div
initial={{ scale: 0.8, opacity: 0 }}
animate={{ scale: 1, opacity: 1 }}
exit={{ scale: 0.8, opacity: 0, dur: 0.1 }}
transition={{ type: "spring", duration: 0.4 }}
>
<IconButton
onClick={() => {
window.scrollTo({ top: 0, behavior: "smooth" });
}}
colorScheme="blue"
aria-label="Wróć do góry"
size="lg"
icon={<ArrowUpIcon />}
/>
</motion.div>
</Box>
) : null}
</AnimatePresenceSSR>
);
};

0 comments on commit 8961cf3

Please sign in to comment.