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.
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>
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With