How to create sticky headers on scroll with react
So I have tables that I am trying to classify by date, with headers like (today, yesterday, last week, ...) and I am trying to make them sticky depending on the current table in the viewport. I tried using the react-sticky
library specifically the stacked example
as it seems to be the effect I am looking for but I am unable to recreate it.
Please, am I missing some thing on the library usage.
Also a solution without the library is very welcome
What I have been trying
export default function CustomizedTables() {
const classes = useStyles();
return (<StickyContainer>
<Sticky topOffset={20}>
{(props) => (<div className={reduceCSS.tableHistoryTitle_day}>Today</div>)}
</Sticky>
<TableContainer component={Paper} elevation={0}>
<Table className={classes.table} aria-label="customized table">
<TableBody>
{rows.map((row) => (
<StyledTableRow key={row.name} elevation={0}>
<StyledTableCell align="left" className={classes.iconCell}><AssignmentReturnedSharpIcon className={classes.inputIcon} /></StyledTableCell>
<StyledTableCell align="left">{row.calories}</StyledTableCell>
<StyledTableCell component="th" scope="row">
{row.name}
</StyledTableCell>
<StyledTableCell align="right">{row.fat}</StyledTableCell>
<StyledTableCell align="right">{row.carbs}</StyledTableCell>
<StyledTableCell align="right">{row.protein}</StyledTableCell>
</StyledTableRow>
))}
</TableBody>
</Table>
</TableContainer>
</StickyContainer>
);
}
You can just use position: sticky
and top: 0
in your th
. Here's an example:
https://codepen.io/ipetriniith/pen/JjGeOKQ
Follow the steps outlined above, for a sticky header on ReactJs,
Header.js
const Header = () => {
// Sticky Menu Area
useEffect(() => {
window.addEventListener('scroll', isSticky);
return () => {
window.removeEventListener('scroll', isSticky);
};
});
/* Method that will fix header after a specific scrollable */
const isSticky = (e) => {
const header = document.querySelector('.header-section');
const scrollTop = window.scrollY;
scrollTop >= 250 ? header.classList.add('is-sticky') : header.classList.remove('is-sticky');
};
return (
<>
<header className="header-section d-none d-xl-block">
..add header code
</header>
</>
);
}
Header.css - Custom Style (for your header)
.is-sticky {
position: fixed;
top: 0;
left: 0;
width: 100%;
z-index: 999;
box-shadow: 0 2px 24px 0 rgb(0 0 0 / 15%);
background-color: #ffffff !important;
animation: 500ms ease-in-out 0s normal none 1 running fadeInDown;
padding-top: 0px;
padding-bottom: 0px;
}
Note!
Already compiled via link: https://codesandbox.io/s/sticky-header-dyews?file=/src/App.js