From 25693552aedcf59d756985fe1df0093105edb467 Mon Sep 17 00:00:00 2001 From: Murali Krishna Date: Mon, 21 Sep 2020 15:05:09 +0530 Subject: [PATCH] navbar: Sticky/unsticky navbar based on scroll Edit: components/Navbar.js --- components/Layout.js | 2 +- components/NavBar.js | 42 ++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 41 insertions(+), 3 deletions(-) diff --git a/components/Layout.js b/components/Layout.js index d026146..012bbbe 100644 --- a/components/Layout.js +++ b/components/Layout.js @@ -6,7 +6,7 @@ const layoutStyle = { display: "flex", flexDirection: "column", minHeight: "50vh", - width: "100%" + width: "100%", }; const contentStyle = { diff --git a/components/NavBar.js b/components/NavBar.js index 142bb24..db5d9ff 100644 --- a/components/NavBar.js +++ b/components/NavBar.js @@ -1,5 +1,5 @@ // components/NavBar.js -import React, { useState } from 'react' +import React, { useState, useEffect } from 'react' import { AppBar, Toolbar, Button, IconButton, SwipeableDrawer, List, ListItem, ListItemText, InputBase } from '@material-ui/core'; @@ -77,6 +77,39 @@ function NavBar({ active, search, searchSettings }) { const [ drawerOpen, setDrawerOpen ] = useState(false); const classes = useStyles(); + /* For fancy navbar */ + const [_document, set_document] = useState(null) + const [sticky, setSticky] = useState(true); + const [hasInitialised, setHasInitialised] = useState(false) + const [scrollPosition, setScrollPosition] = useState(null); + + useEffect(() => { + set_document(document) + setScrollPosition(1) + }, []) + + useEffect(() => { + if (scrollPosition) setHasInitialised(true); + }, [scrollPosition]) + + const getScrollPosition = () => { + const scrollPosition = _document.body.getBoundingClientRect() + return scrollPosition.y; + + } + + useEffect(() => { + if (_document && scrollPosition != null){ + const handleScroll = () => { + const currentScrollPosition = getScrollPosition(); + setSticky(currentScrollPosition > scrollPosition); + setScrollPosition(currentScrollPosition); + } + window.addEventListener('scroll', handleScroll); + return () => window.removeEventListener('scroll', handleScroll); + } + }, [sticky, hasInitialised, scrollPosition]); + const navs = [ { title: 'Home', route:`${process.env.ASSET_PREFIX}/`}, { title: 'Events', route: `${process.env.ASSET_PREFIX}/events` }, @@ -88,7 +121,12 @@ function NavBar({ active, search, searchSettings }) { ] return ( - + { setDrawerOpen(true) }} edge="start" className='menuButton' >