简体   繁体   中英

how to scroll from one component to an element of another component?

I have 2 components, Component A and Component B which are rendered in the same page. What I need is to scroll to a div of the Component B once I click on a button in the Component A.

Component B:

import React, { FC, useRef } from 'react';

const Footer: FC<Props> = ({ children }) => {
const commentSection = useRef(null);
const gotoCommentSection = () => window.scrollTo({top: commentSection.current.offsetTop, behavior: "smooth"})

  return (
    <>
      <div className="footerClass" ref={commentSection}>
        <div className="container">{children}</div>
      </div>
    </>
  );
};

export default Footer;

if I insert this button in Component B, the scrolling function is working. But how can I achieve that from the Component A?

 <button type="button" onClick={gotoCommentSection}>Scroll to Area</button>

I think it will work to move useRef up the component tree to Component A along with your scroll function. Then use React.forwardRef to apply that ref to the element in Component B. Looks like this is a decent example: https://stackoverflow.com/a/49832065/9325243

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM