What is the solution for correcting a glitch in smooth scrolling behavior that occurs following the page's initial rendering?

Upon loading the page or when the user updates it, there seems to be an issue with smooth scrolling to the desired position on the site (lower than needed).

How can this be resolved so that everything functions correctly even after the page has finished rendering?

"use client";

import React from "react";
import { Link } from "react-scroll";

interface ButtonNavigationProps {
  navigateTo: string;
  children: React.ReactNode;
}

const ButtonNavigation: React.FC<ButtonNavigationProps> = ({
  navigateTo,
  children,
}) => {
  return (
    <Link
      smooth={true}
      spy={true}
      isDynamic={true}
      to={navigateTo}
      offset={-130}
      duration={650}
      className="flex items-center gap-x-2 px-8 py-3"
    >
      {children}
      <svg
        xmlns="http://www.w3.org/2000/svg"
        height="24"
        viewBox="0 -960 960 960"
        width="24"
        fill="currentColor"
      >
        <path d="m560-240-56-58 142-142H160v-80h486L504-662l56-58 240 240-240 240Z" />
      </svg>
    </Link>
  );
};

export default ButtonNavigation;

There are two scenarios in which the scrolling bug does not occur:

  1. If the user manually scrolls through the site or uses link navigation for a second time (the first attempt did not scroll correctly), then the navigation operates as intended.

  2. If the link lacks smooth behavior, everything works properly upon initial page rendering. However, smooth scrolling is preferred and alternatives have not been found.

This abnormal behavior is likely related to a smooth scrolling bug. Confirming full page load before attempting to scroll did not provide a solution.

Answer №1

"implement customer module";

import React, { useState, useEffect } from "react";
import { Link } from "react-scroll";

interface CustomButtonProps {
  goToSection: string;
  content: React.ReactNode;
}

const CustomButton: React.FC<CustomButtonProps> = ({
  goToSection,
  content,
}) => {
  // State to keep track of page loading status
  const [isPageLoaded, setPageLoaded] = useState(false);

  useEffect(() => {
    // Function to update state when the page fully loads
    const handleCompleteLoad = () => {
      setPageLoaded(true);
    };

    // Check if the page has finished loading
    if (document.readyState === "complete") {
      setPageLoaded(true); // Set true immediately if page is already loaded
    } else {
      // If page not yet loaded, add event listener to trigger after load
      window.addEventListener("load", handleCompleteLoad);
    }

    // Event listener cleanup when component unmounts
    return () => {
      window.removeEventListener("load", handleCompleteLoad);
    };
  }, []); // Run once on component mount

  return (
    <Link
      smooth={true}
      spy={true}
      isDynamic={true}
      to={goToSection}
      offset={-130}
      duration={650}
      className="flex items-center gap-x-2 px-8 py-3"
      isDisabled={!isPageLoaded} // Disable smooth scrolling until page fully loads
    >
      {content}
      <svg
        xmlns="http://www.w3.org/2000/svg"
        height="24"
        viewBox="0 -960 960 960"
        width="24"
        fill="currentColor"
      >
        <path d="m560-240-56-58 142-142H160v-80h486L504-662l56-58 240 240-240 240Z" />
      </svg>
    </Link>
  );
};

export default CustomButton;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating a dynamic parameter name within the state: A step-by-step guide

My goal is to dynamically write errors to the state without hardcoding parameter names. I have an object in state called errors: {} where I aim to record errors as they appear while filling out the form. For example, if there is an error in the email fiel ...

Bug in Transformation of Menu Icon in CSS

Trying to bring life to a menu icon through CSS transformations on pseudo-elements :before and :after attached to a span. Everything goes smoothly when the menu icon transitions into its active state, but upon returning to default, the middle bar of the i ...

Problem with using Jquery DIY slider for multiple purposes

There seems to be an issue with the DIY Slider that I'm using. Whenever I attempt to use this slider more than once on a single page, the second one fails to function. I have exhausted all possible solutions that come to mind. $(".slider").diyslider ...

What is the reason behind the "import statement error" that occurs during yup validation?

When running our code, we are encountering the following error: "Module not found: Can't resolve '@hookform/resolvers/yup'" ...

A guide to loading CSS and JavaScript files asynchronously

Is it possible to use loadCSS (https://github.com/filamentgroup/loadCSS/blob/master/README.md) to allow the browser to asynchronously load CSS and JavaScript? This is what I currently have in my head tag: <link rel="preload" href="http://zoidstudios. ...

Applying CSS text-shadow to an input field can cause the shadow to be truncated

I've encountered an issue when applying text-shadow to an input field, where the shadow appears to clip around the text. Here is the CSS code I used: @import url('https://fonts.googleapis.com/css2?family=Jost:ital,wght@0,100..900;1,100..900& ...

What is the best way to vertically and horizontally center an AngularJS Material card (md-card)? (For Angular 1.x)

I am facing a dilemma that seems to have a straightforward solution, yet I cannot seem to find it. Currently, I am creating a basic login page with an angular material card (md-card) as the main component. Within this card, I have included all the necessar ...

Can you demonstrate how to implement a useState hook as a prop in a component using TypeScript and React?

I have a pair of elements and Currently, I am passing a useState hook from Admin component to Login component as a setAuth prop In my Admin element: const Admin = () => { const [authState, setAuthState] = useState(false); <Login setAuth={set ...

Styling with CSS3: positioning floating divs on top of a non-floated div

Checkout this fiddle here: http://jsfiddle.net/PA5T5/1/ I've got a setup with 3 divs - 2 are floated whereas one is not. The two floating divs are positioned on top of the non-floating div. I'm wondering if this approach is correct or if it&apos ...

Adjust the font size based on the width of the parent element

I'm in the process of designing a website that is intended to fully occupy the screen. To achieve this, I have used percentage-based dimensions for all elements. One specific element, a sidebar, has been set to be 30% of the browser window width via ...

Material UI autocomplete with multiple lines of options

I'm attempting to create an autocomplete feature that displays the firstName and lastName of a user on the first line and their id on the second. Here is my current implementation: <Autocomplete freeSolo disableClearable op ...

Customizing the appearance of map items in a React JS application

As a newcomer to reactjs, I am working with an array that looks like this: const mediumNames = ["TAMIL Medium", "ENGLISH MEDIUM"] Using the above code, I have created two cards: const [selectedMediumColor, setSelectedMediumColor] = useState('') ...

When I scroll down, the <div> below the <header> disappears, but only the header should be invisible. Can anyone explain why this is happening?

Check out this JsFiddle link for reference. I have implemented the Material Design Lite framework in my project. In the header section, I want to include a Title row, a row that displays a description (labeled as Story followed by some text), and a row fo ...

Creating square images in CSS without specifying their dimensions can easily be done by centering

Is there a way to create square images from rectangular ones in CSS, while ensuring they remain centered on the page? I have come across numerous solutions that use fixed pixel sizes, but I need my images to be responsive and set in percentages. Essential ...

What is the best way to adjust the height and width of a Modal in a react-bootstrap

I'm currently working on implementing a React Bootstrap Modal in my project. However, I am facing an issue where the dialog appears to be too small for my requirements. I would like to make it bigger, but despite completing the code, it seems that the ...

Tips for making a reusable function that utilizes alternating if statements

After hours of experimenting, I finally achieved a smooth scrolling effect with a bounce at the top and bottom. Now, my challenge lies in creating reusable and clean code for this implementation. Perhaps implementing an algorithm could solve this issue? T ...

How can we ensure that inputs in Asp.Net MVC 5 with Bootstrap fit the screen width?

I'm having trouble getting my textboxes to match the size of my buttons below in the cshtml file. I've made several changes, but nothing seems to work. Here is a snippet from my cshtml file: @model SomeModel.Models.LoginViewModel <div class ...

What steps are involved in implementing an ordering system on a restaurant's website using React?

As I work on developing my portfolio using React, I'm interested in incorporating an online ordering feature. However, the information I have found through Google so far hasn't fully addressed my questions. Can anyone provide guidance on the best ...

Arrange five columns in a bootstrap layout with the first column aligned to the left, the last column aligned to the right, and the remaining columns spaced

I am looking to update my template that was originally created using bootstrap 3.3. There is a div with the following classes: col-md-offset-2 col-md-8 Within this div, there are two rows. The second row will have five social media icons, but I am struggl ...

Adjust background color as you scroll

Is there a way for me to smoothly change the background color to a solid color as I scroll? I want the transition to happen seamlessly. Check out this link for an example <div class="sticky-nav"> </div> .sticky-nav{ position: fixed; widt ...