How to scroll at bottom in react on button

Viewed 11748

I am trying to scroll down user at bottom when user click on button . I really tried hard but didn't find any solution . Could someone please help me how to achieve my goal .

Thanks

4 Answers

You can use document.body.offsetHeight to get the height of the page and scroll to it using windows.scroll. If you need to support IE11 and lower use window.scroll(0, document.body.offsetHeight);

import React from 'react';

function App() {

  function handleScroll() {
    window.scroll({
      top: document.body.offsetHeight,
      left: 0, 
      behavior: 'smooth',
    });
  }

  return <button type="button" onClick={handleScroll}>Scroll</button>;

}

There are few ways to achieve this:

const onClick = () => {
  window.scroll({
    bottom: document.body.scrollHeight, // or document.scrollingElement || document.body
    left: 0,
    behavior: 'smooth'
  });
}

...

return <button onClick={onClick} ... />

and another way with a ref. You need to add an element to the bottom of the page and scroll to it after button clicked:

const bottomRef = React.useRef();

const onClick = () => {
  bottomRef.current.scrollIntoView();
}

...

return (
  <div className="container">
    <button onClick={onClick} />
 
    <div className="bottomContainerElement" ref={bottomRef} />
  <div>
)

You install react-scroll-button npm package

npm i react-scroll-button

Usage code

import React, {Component} from 'react'
import ScrollButton from 'react-scroll-button'
 
class ScrollComponent extends Component {
    render() {
        return (
            <ScrollButton 
                behavior={'smooth'} 
                buttonBackgroundColor={'red'}
                iconType={'arrow-up'}
                style= {{fontSize: '24px'}}
            />
        );
    }
}

You can use useRef hook to scrool to particular div. This is the most recommended method by react and using react hooks.

App.js

import React, { useRef } from "react";
import "./styles.css";

export default function App() {
  const divRef = useRef();

  return (
    <div className="App">
      <button
        onClick={() => {
          divRef.current.scrollIntoView({ behavior: "smooth" });
        }}
      >
        Scroll to Bottom
      </button>
      <div className="bigDiv" />
      <div className="bigDiv" />
      <div className="bigDiv" />
      <div className="bigDiv" ref={divRef}>
        Scrolled Here
      </div>
    </div>
  );
}

Styles.css

.App {
  font-family: sans-serif;
  text-align: center;
}
.bigDiv {
  height: 100vh;
  width: 100%;
  background: cyan;
  border: 1px solid violet;
}

Related