Skip to content

Commit

Permalink
navbar: Sticky/unsticky navbar based on scroll
Browse files Browse the repository at this point in the history
Edit:
components/Navbar.js
  • Loading branch information
LaRuim authored and vrajashkr committed Sep 22, 2020
1 parent 23f32b6 commit 2569355
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 3 deletions.
2 changes: 1 addition & 1 deletion components/Layout.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ const layoutStyle = {
display: "flex",
flexDirection: "column",
minHeight: "50vh",
width: "100%"
width: "100%",
};

const contentStyle = {
Expand Down
42 changes: 40 additions & 2 deletions components/NavBar.js
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -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` },
Expand All @@ -88,7 +121,12 @@ function NavBar({ active, search, searchSettings }) {
]

return (
<AppBar position="static" className='navbar'>
<AppBar className='navbar' style={
{transform: sticky ? "translateY(0%)" : "translateY(-100%)",
transition: 'transform 0.3s ease-in',
position: 'sticky',
top: '0'}
}>
<Toolbar>
<IconButton onClick={() => { setDrawerOpen(true) }} edge="start" className='menuButton' >
<MenuIcon />
Expand Down

0 comments on commit 2569355

Please sign in to comment.