Nika Kurashvili
Nika Kurashvili

Reputation: 6472

scrollToTop doesn't work in react (codesandbox)

In react, I am trying to make scrollToTop work.

Somehow, It doesn't work.

https://codesandbox.io/s/quiet-shape-5iov0?file=/src/App.js Here is the codesandbox. scroll down and there's should be button, called click which scrolls up, but it doesn't work.

Upvotes: 0

Views: 69

Answers (4)

akhtarvahid
akhtarvahid

Reputation: 9779

Try this if you just need to scroll top.

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

function

const nice = () => {
    window.scrollTo({
      top: 0,
      left: 0,
      behavior: "smooth"
    });
  };

Another way using scrollIntoView()

const nice = () => {
    document.querySelector("body").scrollIntoView({
      behavior: "smooth"
    });
  };

For better understanding, checkout window.scrollTo

Upvotes: 3

Shivam Gupta
Shivam Gupta

Reputation: 26

If you dont want to use window object

    const nice = () => {
    const root = document.querySelector("body");
    console.log(root, " root");
    root.scrollIntoView({
      behavior: "smooth"
    });
  };

Upvotes: 0

Mehdi Faraji
Mehdi Faraji

Reputation: 3846

You can scroll to top by using the window object like this :

  window.scrollTo(0,0)

Upvotes: 0

androidoverlord
androidoverlord

Reputation: 301

The scrollTo is a window function so just attach it there:)

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

Upvotes: 0

Related Questions