skip to Main Content

I have a "Header" component and a separate "Main Page", which displays the rest of the components, such as "AboutUs", including the "Header" itself. How to make it so that when you click on the navbar item in the Header component, the Main component scrolls the page to, for example, the "About Us" container.
Thank you.

scroll to a component from clicking navbar button in another component

2

Answers


  1. I would advise using react-scroll. I’ve used it myself many times.

    Wrap the component you want to scroll to with Element component and give it a unique name as the name prop:

    <Element name="myComponent">
      // your component code here
    </Element>
    

    Create a Link component wherever you want to trigger the scroll to the myComponent. Pass the to prop with the same name value of the Element component:

    <Link to="myComponent" smooth={true} duration={500}>
      Scroll to my component
    </Link>
    

    You can check for customization options of the Link component on their page

    Login or Signup to reply.
  2. You can use an anchor to "focus" the div

    <div id="aboutUs"></div>
    

    and then use the following javascript:

    location.href = "#aboutUs";
    

    or you can do it below:

           function onClickHeaderItem(sectionId){
               document.getElementById(sectionId).scrollIntoView()
    
              //location.href = "#aboutUs";
        
        }
    <main>
        <header>
           <div id="headerItem" onClick={() => onClickHeaderItem('aboutUs')}>
              About Us
           </div>
        </header>
    
        <section id="aboutUs">
         About Us Section Here :)
        </section>
    </main>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search