Home > front end >  React; go to specific location on web page when button is clicked on another component
React; go to specific location on web page when button is clicked on another component

Time:02-03

I have 2 different components which are appearing on the same URL(page) and what I want to achieve is, when the button is clicked on Component A it would take me to the Component B location which is on the same page. So with basic HTML this is what I want to achieve;

<a href="#linkToDiv">Scroll me down</a>


<div id="linkToDiv">
Scrolled
</div>

How can I achieve this with React/Next.js

CodePudding user response:

If you want to jump to the component your example will already work.

As your react code will be validated and written into the DOM, it will work the same way.

If you want to scroll with an animation to the component you can use vanillajs's scrollTo function: https://developer.mozilla.org/de/docs/Web/API/Window/scrollTo

<a href="#" onClick={e => {
  e.preventDefault() // do not follow the link
  const targetElement = document.getElementById('linkToDiv')
  const {top, left} = targetElement.getBoundingClientRect() //get position on screen
  window.scrollTo(top   window.scrollY, left   window.scrollX)
/>

CodePudding user response:

Solved it by creating const scrollRef = useRef() on the Page that has both Component A and B. Passed scrollRef to Component A as prop, and wrapped Component B with div

<div ref={scrollRef}> 
  <ComponentB/> 
</div>

Inside Component A which scrollRef has passed as prop; created a function

const scrollBottom = e => {
    e.current.scrollIntoView({
      behavior: "smooth"
    });
  };

and used this on a button as onClick.

<button onClick={() => scrollBottom(scrollRef)}>
    Scroll Down
</button>
  •  Tags:  
  • Related