Effortless navigation with smooth scrolling on anchor links in react/next.js

Can smooth scrolling be achieved using only CSS when clicking on an anchor link within a react component?

...
render(
    <a href="#smooth-link">Link To There</a>
    ....
    <div id="smooth-link">
        ....
    </div>
)

Answer №1

Consider this method for smooth scrolling:

/**
 * Utilizing smooth scrolling within a specified element
 */
#my-element {
    scroll-behavior: smooth;
}

/**
 * Applying smooth scrolling to the entire document
 */
html {
    scroll-behavior: smooth;
}

Source

However, some may argue that JavaScript provides a more effective solution:

document.querySelectorAll('a[href^="#"]').forEach(anchor => {
    anchor.addEventListener('click', function (e) {
        e.preventDefault();

        document.querySelector(this.getAttribute('href')).scrollIntoView({
            behavior: 'smooth'
        });
    });
});

If interested, you can explore this approach further in the documentation.

Answer №2

My previous experience involved utilizing tailwindcss, however, I discovered that it can still function without the need for tailwindcss. All that is required is to include scroll-behavior:smooth in the html tag. Navigate to your project's global .css file and insert this line at the beginning.

html {
  scroll-behavior: smooth;
}

Answer №3

Make sure to attach a click listener to the anchor tag within the <Link> element:

 <Link href="#about">
     <a className="nav-item" onClick={scrollHandle} id="about-">About Us</a>
 </Link>

Here is the scrollHandler function for reference:

 const scrollHandle = (e) => {
  e.preventDefault();
  let id = e.target.id;
  let position = document.getElementById(id.slice(0, id.length - 1)); //remove last dash from id
  window.location.href = "#" + id.slice(0, id.length - 1); //update URL
  position && position.scrollIntoView({ behavior: "smooth", block: "start" }) // smoothly scroll to target
 }

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

`The search bar and search button`

On mobile, I have a search field and a button working fine. However, when typing in something and hitting "search" on the phone's keyboard, it leads to a 404 error. But clicking the "search" button works as expected. I would like to be able to hit "se ...

What is it about that that ticks off so many different boxes?

Hey there! I've been working on creating checkboxes within next js that iterate through each filter and its options. Fortunately, I managed to get it up and running smoothly. However, I'm encountering an issue where checking one option in a speci ...

Exploring and listing the key-value pairs from several arrays within an object

My inquiry pertains to the following function: function loadConfigurations(configs){ console.log(configs); } The 'configs' object received by the loadConfigurations function contains two properties --two arrays named "assigned" and "unassign ...

Issue: React child must be a valid object - Runtime Error Detected

As I delve into the world of React, NextJs, and TypeScript, I stumbled upon a tutorial on creating a navbar inspired by the 'Strip' style menu. It has been quite a learning journey for me as a newbie in these technologies. After seeking help for ...

Swapping a value within an array and moving it to a new position

Consider this scenario: I am dealing with a list of arrays containing values like: let data = [ "10-45-23:45", "10-45-22:45", "10-45-20:45", "10-45-23:45", "10-45-23:59,00:00-04:59", "10-45-23:59, 0 ...

What is the best way to add a button click event listener that persists through DOM changes, such as in a single-page application?

I have developed a ViolentMonkey userscript that adds an event listener to a button with the ID #mark-watched. When this button is clicked, it automatically triggers a click on the button with the ID #next-video. This functionality is necessary because the ...

Can CSS be used to target HTML elements that come after another regardless of their position in the document?

Is there a way to style any <h1> element(s) that come after an <h2> element using only CSS? I've searched through countless pages of CSS documentation, trying to figure out if it's possible to target specific elements that appear AFT ...

Tips for creating a seamless merge from background color to a pristine white hue

Seeking a seamless transition from the background color to white at the top and bottom of the box, similar to the example screenshot. Current look: The top and bottom of the box are filled with the background color until the edge https://i.stack.imgur.com ...

Using jQuery to Validate Input Text Control Depending on Radio Selection

How can I ensure that the input text linked to the selected radio option is filled in? For instance, in the example above: If Contact 1's Email radio option is chosen, the Email text field for Contact 1 must not be empty, while the Phone and US Mai ...

Learn how to upload an image using Vue.js and then trigger a custom method

Greetings! I am a newcomer to Vue.js and I have encountered a problem that I need help with. In my component, there is a hidden input for files. When I click a button, the browser displays a window for importing files from my PC. Once I choose a file, I wa ...

Using the spread operator in ES6 allows for arguments to be placed in a non-con

When working in nodeJS, my code looks like this: path = 'public/MIN-1234'; path = path.split('/'); return path.join( process.cwd(), ...path); I was expecting to get: c:\CODE\public/MIN-1234 but instead, I got: `‌publ ...

The vanishing act of custom fonts in Internet Explorer

This issue with a custom font embed is new to me. I have successfully used custom fonts on many client sites without any problems. One specific client has their own custom font files that are causing trouble. The application in question is embedded in an ...

Arranging elements within a complex div structure

I have been working on styling this div that displays the products for an e-commerce website. I initially used CSS and a table within it, but it seems like using tables for content is not recommended, so I am trying to find a better solution. However, my a ...

Ways to eliminate a component by selecting a different one in React

Hey everyone, I'm fairly new to React and I've encountered a problem. I'm attempting to create an app similar to Trello. Specifically, I need to be able to remove a component when I click on the close icon of another component. Below is the ...

Excessive whitespace bordering the perimeter of the webpage

I've recently delved into the world of HTML/CSS and I'm working on creating a simple website. However, I'm encountering some white space-related issues above the header/body and around the sides. Despite trying various adjustments with margi ...

I am having trouble applying styles to this div tag in the CSS file, as it seems to only work when styling directly in the HTML

In my Search.js file, I have a container for styling the text box that will be displayed in my Home.js file. import React from 'react'; import './Search.css'; import SearchIcon from '@material-ui/icons/Search'; import MicI ...

Changing Image Size in Real Time

Trying to figure out the best way to handle this situation - I need to call a static image from an API server that requires height and width parameters for generating the image size. My website is CSS dynamic, adapting to different screen sizes including ...

Steps for making a grid within a bootstrap 3 modal

I am new to HTML and CSS I'm working on creating a modal content similar to this: https://ibb.co/RvrhmRs Most of the work is done, but my modal currently looks like this: https://ibb.co/1zG0y2t I just need help arranging an icon next to the text. ...

Choosing multiple images by clicking on their alternative text with jQuery

I am currently working on a project that involves clicking on a thumbnail to enlarge the image and display its name (alt) below it. I have made progress, but there seems to be an issue where only one image is displayed no matter which thumbnail I click on. ...

Effortlessly submit multiple forms at once with just a single click using the WordPress form

One issue I'm experiencing is that the forms on my site are generated using shortcodes. I have a suspicion that the buttons I created, which lead to submission form1 and then form2, may not be working properly because of this. This is the current set ...