Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react scroll to component

Tags:

scroll

reactjs

I have 3 components which is my site. Each component js-file is loaded and all 3 shows on one page like this:

Topmenu SectionOne SectionTwo

In the Topmenu component I have a menu only. I’ve tried to setup the scrollToComponent onClick at a menu field (SectionOne). But I cannot figure out how to get it to scroll to SectionOne when clicked?

I know this.sectionOne is a ref to an internal ref, right? But how to direct it to a ref inside the “sectionOne.js” file?

I have the following inside my TopMenu.js file

     onClick={() => scrollToComponent(this.sectionOne , { offset: 0, align: 'top', duration: 1500})}
like image 350
Mads Avatar asked Mar 23 '26 09:03

Mads


1 Answers

To forward the ref to somewhere inside the component, you can use the logic of forwardRef.

This means that we create the ref in the parent component and pass the same to the component which passes it down to DOM element inside it.

class App extends React.Component {
  constructor(props) {
    super(props);
    this.section1 = React.createRef();
    this.section2 = React.createRef();
    this.scrollToContent = this.scrollToContent.bind(this);
  }
  scrollToContent(content) {
    switch(content) {
      case 1:
        this.section1.current.scrollIntoView({behavior: 'smooth'});
        break;
      case 2:
        this.section2.current.scrollIntoView({behavior: 'smooth'});
    }
  }
  render() {
    return (
      <main>
        <Menu goTo={this.scrollToContent} />
        <div className='main'>
          <Section1 ref={this.section1} />
          <Section2 ref={this.section2} />
        </div>
      </main>
    );
  }
}

and then, inside Section1,

const Section1 = React.forwardRef((props, ref)=>{
  return (
    <section ref={ref} className='section'>
      <p>Section 1</p>
    </section>
  );
});

You can see a working sample here

I'm not using scroll-to-component package, but the same thing applies.

Forward Refs are supported only in React 16.3 now, you can use this alternative approach if you need the feature in lower versions.

like image 195
Agney Avatar answered Mar 26 '26 13:03

Agney



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!