D
D
Denis_81062021-12-03 15:57:01
React
Denis_8106, 2021-12-03 15:57:01

How to make a button for smooth scrolling to the top of the page (React)?

Guys, a trivial question is how to make a smooth scroll button in React. I did something like this:

import React from 'react';
import './BtnScrollUp.scss'

function BtnScrollUp() {
  
  const handlerScrollUp = () => {
    if (document.body.scrollTop > 0 || document.documentElement.scrollTop > 0) {
      window.scrollBy(0, -50);
      setTimeout(handlerScrollUp, 10);
    }
  }
  
  return (
    <div className={'btn-scroll-up'} onClick={handlerScrollUp}>&#9650;</div>
  );
}

export default BtnScrollUp;


But I want to make a more beautiful solution, I don’t want to directly knock on the DOM.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Mikhail Osher, 2021-12-03
@miraage

No recursive timeouts needed. Just one challenge.

window.scrollTo({
  top: 0,
  left: 0,
  behavior: 'smooth',
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question