How to use ref and scrollIntoView In HTML

In this approach, we are using the useRef hook to create a reference to the target element and the scrollIntoView method to smoothly scroll to this element. When the button is clicked, the scrollToElement function is triggered, causing the page to scroll to the element referenced by geeksForGeeksRef.

Example: The below example demonstrates the scolling to an HTML element using ref and scrollIntoView.

JavaScript
// page.js this is the entry point of application

"use client";
import { useRef } from 'react';
const App = () => {
  const geeksForGeeksRef = useRef(null);
  const scrollToElement = () => {
    if (geeksForGeeksRef.current) {
      geeksForGeeksRef.current.scrollIntoView({ behavior: 'smooth' });
    }
  };
  return (
    <div style={{ padding: '20px' }}>
      <h3>Approach 1: Using ref and scrollIntoView</h3>
      <button onClick={scrollToElement}
                style={{ marginBottom: '20px' }}>
        Scroll to w3wiki
      </button>
      <div style={{ height: '100vh' }}></div>
      <h1 ref={geeksForGeeksRef} 
          style={{ color: 'green' }}>
        w3wiki
      </h1>
    </div>
  );
};
export default App;

Start your application using the following command.

npm run dev

Output:

How To Scroll To An HTML Element In NextJS?

NextJS has various features that enable smooth scrolling to HTML elements. One method involves using useRef to create a reference to the target element and scrollIntoView to achieve smooth scrolling. Another method, using useEffect and window.scrollBy, sets up an event listener on a button for smooth scrolling when clicked, with useRef hooks to reference elements.

Similar Reads

Prerequisites

NextJSJavaScriptReactJS...

Steps to Setup a NextJS App

Step 1: Create a NextJS application using the following command and answer a few questions....

Using ref and scrollIntoView

In this approach, we are using the useRef hook to create a reference to the target element and the scrollIntoView method to smoothly scroll to this element. When the button is clicked, the scrollToElement function is triggered, causing the page to scroll to the element referenced by geeksForGeeksRef....

Using useEffect and window.scrollBy

In this approach, we are using useEffect to set up an event listener on the button, which triggers window.scrollBy to smoothly scroll to the target element when clicked. The useRef hooks are used to reference both the button and the target element....