Sticky sidebar with higher height content than view-height

Viewed 29

I'm making an ecommerce with reactjs and I need to add a sticky sidebar in the results page. The sidebar content is dynamic. I was trying to make a sidebar like the one on the right here without success https://blog.timekit.io/google-oauth-invalid-grant-nightmare-and-how-to-fix-it-9f4efaf1da35 (please view this page in a window shorter than 1080px so you can watch how it works). I want to replicate the way it works, when I scroll down the sidebar has a position relative, but when its content reaches the end the position changes to sticky, and if I scroll up the position changes to relative again, and when the content reaches the start the position changes to sticky again. Here is my code (I set the stickyContainerHeight inside a useEffect), the relativeContainer state is to change the position dynamically but I haven't used it yet.

  const [lastWindowScroll, setLastWindowScroll] = useState(0);
  const [stickyContainerHeight, setStickyContainerHeight] = useState(0);
  const [relativeContainer, setRelativeContainer] = useState(false);

  useEffect(() => {
    const controlWindowScroll = () => {
      if (window.scrollY < lastWindowScroll) {
        setRelativeContainer(false);
      } else {
        setRelativeContainer(true);
      }

      setLastWindowScroll(window.scrollY);
    };

    window.addEventListener("scroll", controlWindowScroll);

    return () => {
      window.removeEventListener("scroll", controlWindowScroll);
    };
  }, []);

<div>
  <div style={{position: "relative" }}>
    <div
      style={{
        position:
          windowScroll === 0 ||
          stickyContainerHeight - window.innerHeight < windowScroll
            ? "sticky"
            : "relative",
        top:
          windowScroll === 0 ||
          stickyContainerHeight - window.innerHeight < windowScroll
            ? ---
            : ---,
        marginTop:
          windowScroll === 0 ||
          stickyContainerHeight - window.innerHeight < windowScroll
            ? ---  when the position is relative I need to add
            : ---, margin top, but I don't know how much
      }}
    >
      <h1> CONTENT </h1>
      <h1> CONTENT </h1>
      <h1> CONTENT </h1>
      <h1> CONTENT </h1>
    </div>
  </div>
</div>

I can't figure out where the top and marginTop numbers come from.

0 Answers
Related