Mads
Mads

Reputation: 57

react scroll to component

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})}

Upvotes: 3

Views: 17594

Answers (1)

Agney
Agney

Reputation: 19224

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.

Upvotes: 7

Related Questions