Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Scroll with offset

I've managed to implement scrolling in react using HashLink but I encounter a problem. I have a sticky menu and the scroll will go to the component needed but it will be blocked by the menu. I need like a 48px offset. I tried to implement with HashLink but I get errors that it's not a function, can you guys help me? For the context Every section including the header with the links is a separate component my layout is:

Section1 id = "header"

Section2 id = "audiance"

etc

Where Section 1 = header with the links. Thats why I use "/#" because I set an id to the components to make the link work

Scrolling with no offset:

 state = {
        page : [
            {
                name : 'About',
                linkTo : '/#about'
            },
            {
                name : 'Features',
                linkTo : '/#audiance'
            },
            {
                name : 'Contact',
                linkTo : '/#contact'
            }
        ]
    };

    populateLinks = (item, i) => (
        <li className="nav-item" key = {i} > <HashLink smooth className="nav-link" to={item.linkTo} >{item.name}</HashLink> </li>
    )

Partial implementation of offset but with errors:

   scrollWidthOffset = (el) => {
        const yCoordinate = el.getBoundingClientRect().top + window.pageYOffset;
        const yOffset = -80; 
        window.scrollTo({ top: yCoordinate + yOffset, behavior: 'smooth' }); 
    }
    


    populateLinks = (item, i) => (
        <li className="nav-item" key = {i} > <HashLink smooth className="nav-link" to={item.linkTo} scroll={el => this.scrollWithOffset(el)}>{item.name}</HashLink> </li>
like image 368
Blaj Bogdan Avatar asked Dec 07 '25 08:12

Blaj Bogdan


1 Answers

scrollWidthOffset = (el) => {
  const menu = document.getElementById('menu')
  window.scrollTo({
      top: el.offsetTop - menu.offsetHeight,
      behavior: "smooth"
    });
}

you can also use the container element instead of window, but then you need to set overflow: scroll on it.

like image 135
Michal Reifer Avatar answered Dec 08 '25 21:12

Michal Reifer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!