Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scroll down the page to another React component on a button click

I have two React Components

<Component A> 
    ........ some more code here ..................
    <button> This is a button </button>
    ........ some more code here .................. 
</Component A>

another component is

<Component B> 
    ........ some more code here ..................
    <div> This is a Component </div> 
    ........ some more code here ..................
</Component B>

One parent Homepage component renders both of these components

<Homepage>  
  ........ some more code here ..................
  <Component A />
  <Component B />
  ........ some more code here ..................
</Homepage>

I want to achieve a scenario like whenever the button in Component A is clicked the webpage which is actually the Homepage Component will scroll down to Component B. I have achieved this behavior whenever the button and the Component B is in the same component, But I am not sure how can I achieve the same when there are two separate components. So far I thought like this

import React, { useRef } from 'react';

const scrollToDiv = (ref) => window.scrollTo(0, ref.current.offsetTop);

const SingleComponent = () => {

   const compRef = useRef(null);
   const isScroll = () => scrollToDiv(compRef);

   return (
      <> 
         <button onClick={isScroll}> Show More </button>
         ........ some more code here ..................
         <div ref={compRef}>This is the Component</div> 
      </>
   )
}

This code is working fine when the button and the area it should scroll to is in the same component. But when the button and the area it should scroll to are in different components, I am not sure how it should work.

like image 608
ashfaqrafi Avatar asked Dec 22 '25 01:12

ashfaqrafi


1 Answers

References can be passed down the chain

const Parent = function(){
 const scrollToDiv = (ref) => window.scrollTo(0, ref.current.offsetTop);
 const el1 = useRef();
 const el2 = useRef();
 return (
   <>
    <Child reference={el1} click={()=> scrollToDiv(el2)} />
    <Child reference={el2} />
   </>
  );  
}

const Child = function({ reference, click }) => (
  <div ref={reference}>
    <button onClick={click}></button>
  </div>
);
like image 75
Petrov. Ivan Petrov Avatar answered Dec 23 '25 16:12

Petrov. Ivan Petrov