0

I am trying to create a smooth scrolling page in React. The page is split into 4 sections:

Overview

About us

Courses

News

So on scrolling, if it's at the section 'News' with the id=news the URL should be updated to: website.com/specific-string#news so he can copy this link, and when you access this URL to send you directly to that section.

I am using react version 16.3.1. So cannot use hooks here.

After adding this smooth scroll feature, I need to display a button which will download the content in the section in the viewport. I am new to react and trying to learn new things by challenging myself everyday. Anyone who could guide me here?

3
  • Is there any particular reason you don't want to use hooks? Commented Feb 7, 2023 at 13:32
  • I want to explore the possibilities with class based components. Commented Feb 7, 2023 at 13:46
  • Then you could achieve that with just javascript, you can check if an element is inside the viewport and manipulate whatever when it happens. I remember doing something similar with the help from this post Commented Feb 7, 2023 at 14:01

2 Answers 2

0
window.location.hash = element.id  // here is the element id

Or like this if you do not want to scroll to the element

history.pushState({}, "", element.id)

You can update your location hash like this.

If you don't know how to get the element id, you can use IntersectionObserver

It all can be done without hooks

Sign up to request clarification or add additional context in comments.

Comments

0

For Download function and scroll handling, You can add below function to your code:

const handleDownload = () => {
  const currentSection = window.location.hash.substr(1);
  const element = document.getElementById(currentSection);
};

// For Scroll functionality
handleScroll = () => {
    const sections = ['overview', 'about', 'courses', 'news'];
    const scrollPosition = window.scrollY;

    sections.forEach(section => {
      const element = document.getElementById(section);
      if (element) {
        const { top, bottom } = element.getBoundingClientRect();
        if (top <= 0 && bottom >= 0) {
          window.history.replaceState(null, '', `#${section}`);
        }
      }
    });
  };

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.