Reputation: 16102
How can I autohide my Reactjs <AppBar/>
component when scrolling as shown in Fig.1?
<AppBar/>
autohides when scrolling
I am using Material-UI and my code is as follows.
MyAppBar.jsimport React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core/styles';
import AppBar from '@material-ui/core/AppBar';
import Toolbar from '@material-ui/core/Toolbar';
import Typography from '@material-ui/core/Typography';
import Button from '@material-ui/core/Button';
import IconButton from '@material-ui/core/IconButton';
import MenuIcon from '@material-ui/icons/Menu';
const styles = {
root: {
flexGrow: 1,
},
grow: {
flexGrow: 1,
},
menuButton: {
marginLeft: -12,
marginRight: 20,
},
};
function ButtonAppBar(props) {
const { classes } = props;
return (
<div className={classes.root}>
<AppBar position="static">
<Toolbar>
<IconButton className={classes.menuButton} color="inherit" aria-label="Menu">
<MenuIcon />
</IconButton>
<Typography variant="h6" color="inherit" className={classes.grow}>
News
</Typography>
<Button color="inherit">Login</Button>
</Toolbar>
</AppBar>
</div>
);
}
ButtonAppBar.propTypes = {
classes: PropTypes.object.isRequired,
};
export default withStyles(styles)(ButtonAppBar);
Upvotes: 3
Views: 4497
Reputation: 14191
You can use Slide
in conjuction with useScrollTrigger
The gist here is, useScrollTrigger
will (by default) return true
when you scroll down and the window vertical scrollbar position hits a certain threshold (100
pixels from origin by default) - when you scroll back up it returns false
. Hence, these are the reasons why we negate it on the in
prop of Slide
export default function HideAppBar() {
const trigger = useScrollTrigger();
return (
<>
<Slide appear={false} direction="down" in={!trigger}>
<AppBar>
<Toolbar>
<Typography variant="h6">Scroll Down to Hide App Bar</Typography>
</Toolbar>
</AppBar>
</Slide>
...
</>
);
}
You can use the link I gave at the top of this answer pertaining to useScrollTrigger
to customize the options such as threshold
Reference: https://material-ui.com/components/app-bar/#hide-app-bar
Upvotes: 7