How to create sticky headers on scroll with react

Viewed 44503

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>
  );
}
4 Answers

Follow the steps outlined below, 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

In react you need to set the class by calling a useState function.

You can set the listener for this in a useEffect that runs once on component render.

import React, { useEffect, useState } from "react";

const Header = () => {
  const [sticky, setSticky] = useState("");

  // on render, set listener
  useEffect(() => {
    console.log("hello");
    window.addEventListener("scroll", isSticky);
    return () => {
      window.removeEventListener("scroll", isSticky);
    };
  }, []);

  const isSticky = () => {
    /* Method that will fix header after a specific scrollable */
    const scrollTop = window.scrollY;
    const stickyClass = scrollTop >= 250 ? "is-sticky" : "";
    setSticky(stickyClass);
    console.log(stickyClass);
  };

  const classes = `header-section d-none d-xl-block ${sticky}`;

  return (
    <>
      <header className={classes}>..add header code</header>
    </>
  );
};

export default Header;

Sandbox here: https://codesandbox.io/s/sticky-header-forked-ybo6j9

Most of this code referenced from this answer: https://stackoverflow.com/a/69944800/271932 (which has correct CSS but not react code)

after reading lots of js code that accomplishes this, I achieved this like so...

.header {
    position: sticky;
    top: 0px;
    z-index: 1;
}
Related