Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

252
Views
How to make sticky side bar that scrolls along with content in next js?

So I have two components, a feed and a sidebar. The sidebar has more content than it can show, so it is allowed to overflow. I want the sidebar to scroll along with the content, but stick when it reaches it ends, however the content can keep scrolling.

The concept is similar to twitter's sidebar + content type.

I found a solution in jQuery, but I really can't figure out how to write the same in Nextjs, which is what I am using.

Here is the example fiddle solution I found, can someone help me write it in react/next js ?

How do i solve this ??

This is the fiddle I found

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

I figured out the solution myself, I wrote it in a react friendly way so people wouldn't have to break their head on it!

Here you go:

function handleScroll() {
        if(window.innerHeight <1000) {
            if(bottomVisible()) {
                document.getElementById('side').style.marginTop = ` ${ window.scrollY - sidebarRef.current.offsetHeight + window.innerHeight}px`
            } else if(topVisible()) {
                // document.getElementById('side').style.marginTop = `${window.scrollY}px`;
            } else {
                document.getElementById('side').style.marginTop = `${window.scrollY}px`;
            }
        } else {
            document.getElementById('side').style.position = 'sticky';
            document.getElementById('side').style.top = '0px'
        }
    }

    useEffect(() => {

        window.addEventListener('scroll',handleScroll);
        return () => {
            window.removeEventListener('scroll', handleScroll);
        }
    
    },[])

    function bottomVisible(){
        var rect = sidebarRef.current.getBoundingClientRect();
        if(rect.bottom <= window.innerHeight) {
            return true
        }
        return false
    }

    function topVisible() {
        var rect = sidebarRef.current.getBoundingClientRect();
        if(rect.top <= 0) {
            return true
        }
        return false;
    }

Disclaimer: SidebarRef is a ref I created for the component, and its height is 1000px hence the if-else

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!