Loading...

How to smoothly scroll to a specific content or element in React?

question react front-end
Ram Patra Published on February 19, 2024

To implement scrolling to a specific content or element on click in a React application, you can follow these steps:

  1. Identify the element you want to scroll to by giving it an id.
  2. Implement a function that handles the scrolling behavior.
  3. Attach an event listener, such as an onClick handler, to the element that triggers the scrolling function.

Here’s how you can do it in a React component:

import React from 'react';

function scrollToElement(id) {
  const element = document.getElementById(id);
  if (element) {
    element.scrollIntoView({ behavior: 'smooth' });
  }
}

function MyComponent() {
  return (
    <div>
      <button onClick={() => scrollToElement('myContent')}>
        Scroll to Content
      </button>
      <div style= />
      <div id="myContent">
        Content to scroll to
      </div>
    </div>
  );
}

export default MyComponent;

In this example:

  • We have a button that triggers the scrolling behavior when clicked.
  • The scrollToElement function takes the id of the element to scroll to, finds the corresponding element using document.getElementById, and then calls scrollIntoView on it with { behavior: 'smooth' }.
  • Below the button, there’s a placeholder <div> with some height to create space for scrolling.
  • Following that, there’s the content we want to scroll to, which has the id of 'myContent'.

This example demonstrates scrolling within the same page. If you’re navigating to a different page within a Next.js application and want to scroll to a specific content element on that page, you would typically pass some sort of identifier or reference to the destination page and then trigger the scrolling behavior once the new page is mounted.

Now, to make the above method a bit more polished, we can do two things:

  1. Prevent `#` from being appended to the url on click of an anchor tag
  2. Add a `padding` option which will determine the offset from the top of the element to stop scrolling before
export function scrollToElement(event: React.MouseEvent<HTMLElement, MouseEvent>, id: string, padding: number = 0) {
    event.preventDefault();
    
    const element = document.getElementById(id);
    if (element) {
        const targetPosition = element.getBoundingClientRect().top + window.scrollY - padding;
        window.scrollTo({ top: targetPosition, behavior: "smooth" });
    }
}

Now, you can call this method from an anchor tag like this:

<a href="#" onClick={(e) => {scrollToElement(e, 'myContent', 80)}}>Click</a>

Although the above solution works perfectly fine, I personally prefer this simpler solution that involves only one line of CSS.

Presentify

Take your presentation to the next level.

FaceScreen

Put your face and name on your screen.

ToDoBar

Your to-dos on your menu bar.

Ram Patra Published on February 19, 2024
Image placeholder

Keep reading

If this article was helpful, others might be too

question react front-end February 2, 2024 What's the use of useEffect hook in React?

In React, the useEffect hook is used to perform side effects in functional components. Side effects can include data fetching, subscriptions, manual DOM manipulations, and other operations that cannot be handled during the render phase.

question nextjs react July 19, 2024 How to get the current path in Next.js?

To get the current path in a Next.js application, you can use the usePathname hook from next/navigation module. This hook allows you to access the current pathname within your components. Here’s how you can use it:

question typescript react September 28, 2024 How to add a custom element to a Next.js/Typescript project?

Let’s say I have a custom element setapp-badge that I want to use in my tsx files. If I go ahead and use it, the compiler will throw an error and Next.js will fail to build. It seems the problem might be a combination of how Next.js, TypeScript, and custom elements work together. Therefore, let’s try an approach that avoids the namespace/module issues while ensuring custom elements are recognized in a Next.js/TypeScript project.