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.
// 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.