Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
  );
}
like image 867
bihire boris Avatar asked Jul 18 '20 15:07

bihire boris


People also ask

How do you make a sticky header in Reactjs?

Building the StickyHeader hook isSticky && setIsSticky(true); } else { isSticky && setIsSticky(false); } }, [isSticky] ); useEffect(() => { const handleScroll = () => { toggleSticky(tableRef. current. getBoundingClientRect()); }; window. addEventListener("scroll", handleScroll); return () => { window.

How do I create a header component in React?

Approach: First we will create a basic react app using some installations. We will make our new Header Component with some styling using Material-UI. To create a Header, we will use App Bar from Material UI which will provide screen titles, navigation, and actions.

How do you make a scroll top in React?

Use the window. scrollTo() method to scroll to the top of the page in React, e.g. window. scrollTo(0, 0) . The scrollTo method on the window object scrolls to a particular set of coordinates in the document.


4 Answers

You can just use position: sticky and top: 0 in your th. Here's an example: https://codepen.io/ipetriniith/pen/JjGeOKQ

like image 67
Iván Avatar answered Oct 20 '22 10:10

Iván


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

like image 30
Rigers Leka Avatar answered Oct 20 '22 10:10

Rigers Leka


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)

like image 1
awongh Avatar answered Oct 20 '22 10:10

awongh


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

.header {
    position: sticky;
    top: 0px;
    z-index: 1;
}
like image 1
Jason Bean Avatar answered Oct 20 '22 10:10

Jason Bean