PASSWORD RESET

Your destination for complete Tech news

How to scroll page to the bottom in React JS?

501 0
< 1 min read

To scroll the page to the bottom in a React component, you can use the window.scrollTo() method or use the scrollIntoView() method on a specific element. Here’s how you can do both:

Using window.scrollTo():

import React from 'react';

function ScrollToBottomButton() {
  const scrollToBottom = () => {
    window.scrollTo({
      top: document.documentElement.scrollHeight,
      behavior: 'smooth' // Use 'auto' for instant scrolling
    });
  };

  return (
    <div>
      <button onClick={scrollToBottom}>Scroll to Bottom</button>
      {/* Your content */}
    </div>
  );
}

export default ScrollToBottomButton;

In this example, clicking the “Scroll to Bottom” button will smoothly scroll the page to the bottom using the window.scrollTo() method.

Using scrollIntoView() on an element:

import React, { useRef } from 'react';

function ScrollToBottomButton() {
  const bottomRef = useRef(null);

  const scrollToBottom = () => {
    if (bottomRef.current) {
      bottomRef.current.scrollIntoView({ behavior: 'smooth' });
    }
  };

  return (
    <div>
      <button onClick={scrollToBottom}>Scroll to Bottom</button>
      {/* Your content */}
      <div ref={bottomRef} /> {/* An empty element to scroll to */}
    </div>
  );
}

export default ScrollToBottomButton;

In this example, an empty <div> element with a ref is added to the component. Clicking the “Scroll to Bottom” button will smoothly scroll the page to the element with the specified ref using the scrollIntoView() method.

Remember that smooth scrolling behavior may not be supported in all browsers. You can use the behavior: 'auto' option in both examples to achieve instant scrolling if desired.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.