What is the best way to enhance the smoothness of transitioning to a different section on the same page in React by clicking an anchor tag (<a>

Background

My current method involves an immediate jump to another section without any smooth transition. This is how I implement it:

<a href="#go_middle">Go Middle</a>

<div id="go_middle"&‌​gt;Hello There</div>

Intended Outcome

I am looking to add a transition effect, so that instead of abruptly moving to the section, there is a gradual transition through other parts of the page if applicable.

Answer №1

To ensure smooth scrolling on your website, include this CSS code in the relevant class or id:

.smooth-scroll {
  scroll-behavior: smooth;
}

Alternatively, you can apply the code directly to the HTML tag like so:

html {
  scroll-behavior: smooth;
}

Implementing this will result in a seamless scrolling experience without any sudden jumps on the page.

Answer №2

I'm not very familiar with react, but I did find success using this vanilla javascript code:

document.querySelectorAll('a.smooth-scroll').forEach(anchor => {
        anchor.addEventListener('click', function(e) {
            e.preventDefault();
            document.querySelector(this.getAttribute('href')).scrollIntoView({
                behavior: 'smooth'
            });
        });
    });

Just remember to include 'class: smooth-scroll' in your anchor tag. Let me know if it works for you :)

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

Header alignment issue in JQGrid

Utilizing 4.4.4 - jQuery Grid and <= jquery 1.8.2, this is how I set up my jqgrid: function FAGrid() { var url1 = 'URL'; $("#FAList").jqGrid({ url: url1, datatype: 'json', mtype: 'POST', ...

Unable to retrieve input value in ReactJS with TypeScript

I've just started learning Typescript and I encountered an error while trying to console.log the input field value. Any tips or suggestions on how to handle this? Here's my code: class Register extends Component<{},userState> { state = { ...

What is the best way to override @include within a CSS class?

Our team's application utilizes Bootstrap SASS for styling, but we have made certain customizations to the framework. The Bootstrap files are included in our project through a build process, making direct modifications impossible. When it comes to dr ...

Arrange the parallel table columns within their own individual divs to be perfectly aligned

I have a layout with two divs stacked on top of each other, each containing a table with the same number of columns. I need to ensure that the columns in both tables are the same width and aligned properly. If a column in one table expands, I want the corr ...

Import MDX metadata in Next.js on the fly

I am currently utilizing Next.js to create a static blog site. Following the guidelines in Next.js documentation, I set up @next/mdx and successfully imported MDX statically using import MDXArticle from "@/app/(article)/2023/test-article/page.mdx&quo ...

React Component - Element with an undefined value

When I tried implementing an Ionic Modal as a React Component, I encountered the following error message: Type '({ onClose, tipo }: PropsWithChildren<{ onClose: any; tipo: number; }>) => Element | undefined' is not assignable to type & ...

The toggle function for the hamburger icon is currently malfunctioning

I am facing an issue with the hamburger icon on my website. The toggle functionality associated with it is not working properly. Even though I have a class named change-1 that should be toggled upon clicking the icon, it is not happening. There are no erro ...

A guide on elegantly pausing for the completion of .map() function and generating fresh keys within the array[index]

I am currently working on generating an array with the following values: { name: 'John', age: 35, employer: 'ABC', paycheck: 5,000, last_paycheck: 4,900, change: 100 } // new array and initializing the array with these initial values: ...

Remove the image from the container in Bootstrap

I'm looking to position an image outside the container so that the right margin remains within the default container width (responsive) while keeping the image aligned with a button consistently. Please refer to the image below for clarification: ht ...

How can I make Nav-tabs align vertically on small screens?

I'm struggling to figure out why my .nav .nav-tabs are not stacking vertically even when I am using flex-sm-column. It's frustrating me a lot. Any ideas on what might be causing this issue? <html> <head> <link rel="stylesheet" h ...

Attempting to extract information from website, successful on majority of sites but encountering issues on this particular one

We are looking to extract dividend data specifically from the Nasdaq exchange similar to this Google Sheets example. While most other URLs work without any issues, the query for this one seems to be failing. <?php $ch = curl_init(); curl_setopt($ch, C ...

I find it impossible to avoid using the withRouter and withAlert functionalities in Reactjs

When using withRouter, the alert.success property is not accessible. A TypeError is thrown with the message "Cannot read property 'success' of undefined". This issue prevents the successful display of alerts in my application. The error occurred ...

The positioning of Material UI InputAdornment icons is located beyond the boundaries of the TextField input area

I am struggling to understand why my InputAdornment is not positioned correctly. There doesn't seem to be any style in my code that would affect the location of the icon within the TextField (such as padding or flex properties). Currently, the calen ...

Is it possible to show only a snippet of the title on the main blog page of WordPress

Seeking assistance in displaying a condensed version of a blog post's title on the blog's main page along with a thumbnail image. While I've come across several resources on showcasing post excerpts, I have yet to find information on trimmin ...

From dividing into three sections to splitting into two sections

Struggling to create a list of images and descriptions in sets of threes at larger widths, transitioning to twos at smaller widths? The breakdown is causing chaos. Need help achieving clean one-half columns. Appreciate any assistance! ...

The functionality to Toggle submenus within a navigation menu using jQuery is not performing as anticipated

I implemented a horizontal menu using CSS, HTML, and jQuery. Clicking on a menu item displays a sub-menu. The issue I'm facing is that when one submenu is open and I click on another menu item, the new submenu opens but doesn't hide the previous ...

Plunker is currently experiencing issues with React.js functionality

I'm currently working on a basic React.js Plunker project but it seems to be experiencing some issues. I expected the button to be displayed, however, that is not happening. Can anyone provide assistance and help me identify what's causing the pr ...

Is there a way to extract the unicode/hex representation of a symbol from HTML using JavaScript or jQuery?

Imagine you have an element like this... <math xmlns="http://www.w3.org/1998/Math/MathML"> <mo class="symbol">α</mo> </math> Is there a method to retrieve the Unicode/hex value of alpha α, which is &#x03B1, using JavaScrip ...

The overwriting of SCSS transition properties

I have a handy @mixin that I use to easily add different transition properties to elements. Here's an example of how I use it in my .scss file: @mixin transition($prop, $sec){ -webkit-transition: $prop $sec; -moz-transition: $prop $sec; -ms-tra ...

Is there a file outside of the website's root that needs to be linked?

Hey there, I could use some assistance with a little issue I am having: Running the latest release of Ubuntu server 64bit with 2 virtual websites Here is my folder structure: site1 (Accessible on the web) /var/www/site1 site2 (Intranet site) /var/www ...