40

What is the correct way of dealing with scroll position in React? I really like smooth scrolling because of better UX. Since manipulating the DOM in React is an anti-pattern I ran into problem: how to scroll smoothly to some position/element? I usually change scrollTop value of an element, but this is a manipulation on the DOM, which is not allowed.

JSBIN

code:

import React from 'react';
import ReactDOM from 'react-dom';


class App extends React.Component {
  handleClick = e => {
    for (let i = 1; i <= 100; i++) {
      setTimeout(() => (this.node.scrollTop = i), i * 2);
    }
  };

  render() {
    const someArrayToMap = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

    return (
      <div ref={node => this.node = node} style={{overflow: 'auto', height: '100vh'}}>
        <button onClick={this.handleClick}>CLICK TO SCROLL</button>
        {
            [...someArrayToMap,
            ...someArrayToMap,
            ...someArrayToMap,
            ...someArrayToMap,
            ...someArrayToMap,
            ...someArrayToMap,
            ...someArrayToMap].map((e, i) => <div key={i}>some text here</div>)
        }
      </div>
    );
  }
}


ReactDOM.render(<App />, document.getElementById('root'));

How to achieve this in a React way?

1
  • Remember that manipulating the DOM is an anti-pattern because React is essentially a DOM manager, so it must maintain awareness of everything happening in the DOM; with that said, you can always use things like findDOMNode and getBoundingClientRect to observe DOM nodes directly. Read-only is all good.
    – agm1984
    Mar 11, 2018 at 21:24

10 Answers 10

47

You can just use refs and the scrollIntoView method (with behavior: 'smooth' for smooth scrolling). It's only a few lines of code and doesn't require a package.

Say this is what you want to scroll to

<p ref={this.myRef} className="scrollToHere">[1] ...</p>

And some sort of button

<button onClick={() => {this.scroll(this.myRef)}} className="footnote">[1]</button>

to call the scroll method

class App extends Component {
  constructor() {
    super()
    this.myRef = React.createRef();

  scroll(ref) {
    ref.current.scrollIntoView({behavior: 'smooth'})
  }
}

EDIT: Because this method is not yet supported by all browsers (overview of browser support), you might want to use a polyfill.

7
  • Is this for React Native only or?
    – OZZIE
    Nov 7, 2018 at 12:26
  • Caveat: browser support for the smooth scrolling option on scrollIntoView is limited to Chrome and Firefox as of November 2018
    – Pdnell
    Nov 9, 2018 at 17:36
  • 1
    It's a Javscript method, so it does not depend on React. Here you can see the specification and browser support. Because it is not yet supported by all browsers, you might want to use polyfills. I used this polyfill which worked perfectly for me
    – bbrinx
    Nov 11, 2018 at 17:51
  • This seems to be the best option, if you include the polyfill. When all the browsers will implement this you can simply remove the polyfill and that's it. Thanks for this solution, works great! @sympi you should accept this as the correct answer.
    – Sergiu
    Nov 22, 2018 at 8:26
  • @bbrinx Your link to the polyfill is pointing to the specifications page.
    – JW.
    Dec 24, 2018 at 18:01
47

window.scroll({top: 0, left: 0, behavior: 'smooth' }) works for me.

You also need to check for browser's compability

Or use polyfill


Edit: For the completeness' sake, here is how to dynamically polyfill with webpack.

if (!('scrollBehavior' in document.documentElement.style)) {
//safari does not support smooth scroll
  (async () => {
    const {default: smoothScroll} = await import(
      /* webpackChunkName: 'polyfill-modern' */
      'smoothscroll-polyfill'
      )
    smoothScroll.polyfill()
  })()
}

By this dynamic polyfill, the package is loaded via ajax unless the browser supports the smooth scroll.

polyfill-modern is an arbitrary chunk name, which hints webpack compiler to combine packages together, in order to reduce the number of requests to the server.

1
24

The Simplest way to do: -

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

This simple JavaScript code is working with all browser.

1
  • 1
    This will not work on Safari as of July 2021. See other answers, mainly concerning polyfill Jul 6, 2021 at 20:10
5

Here's a small, no-dependancy solution using hooks

const useSmoothScrollTo = id => {
    const ref = useRef(null)
    useEffect(() => {
        const listener = e => {
            if (ref.current && location.hash === id) {
                ref.current.scrollIntoView({behavior: 'smooth'})
            }
        }
        window.addEventListener('hashchange', listener, true)
        return () => {
            window.removeEventListener('hashchange', listener)
        }
    }, [])
    return {
        'data-anchor-id': id,
        ref
    }
}

You use it like this:

export const FeaturesSection = () => {
    const bind = useSmoothScrollTo('#features')
    return (
        <section {...bind} className={classes.features}>
        ...
        </section>
    )
}      

Then anywhere else in your app you only need to do

<a href="#features">Go to Features</a>

Obviously, same caveats as above apply to .scrollIntoView({behavior: 'smooth'})

2

A couple good packages out there already that can handle this for you:

https://github.com/fisshy/react-scroll - Demo

https://www.npmjs.com/package/react-scroll-to-component Simple scroll to component

Hope this helps!

4
  • @PaulCo the demo at fisshy.github.io/react-scroll-example/basic/index.html is working fine for me Jun 13, 2018 at 16:27
  • is the top left list is supposed to be clickable for scrolling or is it only a style based on view port position ?
    – PaulCo
    Jun 14, 2018 at 14:19
  • Yeah top menu click is scrolling to that page for me in Chrome. Jun 14, 2018 at 14:39
  • Well in FF I've got the console error: ReferenceError: event is not defined, never mind I'll watch this in Chromium !
    – PaulCo
    Jun 15, 2018 at 8:47
2

There are several libraries for scrolling to anchors in React. The one to choose depend on the features you're seeking and the existing setup of your page.

React Scrollable Anchor is a lightweight library that's specifically for scrolling to anchors that are mapped to URL hashes. It also updates the URL hash based on currently focused section. [Full disclosure: I'm the author of this library]

React Scroll, mentioned in another answer, is a more fully featured library for scrolling to anchors, without any reflection of location in the URL.

You can also hook up something like React Router Hash Link Scroll if you're already using React Router, which will then also tie into your URL hash.

1
  • 1
    Since you're the author of a library doing this, and op asked on the how to do this in a react way, without library. (that's how I took the question, and would like the answer to be)
    – Ulysse BN
    Jul 6, 2017 at 22:35
1

I really enjoy the react-router website in the API section, they seem to use this scrollToDoc component that is a really sweet translation of a typical VanillaJS smooth-scroll function into React which depends on react-motion!

1

Just add this code to your App.CSS

html{
    scroll-behavior: smooth;
}

Make sure to use NavLink and give an Id to a particular section.

0

Simple hook:

function useScrollTo(): [string, () => void] {
    const id = useId();
    const handleScroll = useCallback(() => {
        const element = document.getElementById(id);
        if (element) {
            element.scrollIntoView({ behavior: 'smooth' });
        }
    }, [id]);

    return [id, handleScroll];
}

And usage:

function App() {
    const [section2, scrollToSection2] = useScrollTo();

    return (
        <>
            <button onClick={scrollToSection2}>Scroll</button>

            <div id={section2}>Section 2</div>
        </>
    )
}
0

Here's a code in JavaScript that makes use of the window.requestAnimationFrame() method to smoothly scroll to a specified position in React:

function scrollToPosition(position) {
  let startPosition = window.pageYOffset;
  let distance = position - startPosition;
  let startTime = null;

  function animation(currentTime) {
    if (startTime === null) startTime = currentTime;
    let timeElapsed = currentTime - startTime;
    let scrollTop = easeInOutQuad(timeElapsed, startPosition, distance, 700);
    window.scrollTo(0, scrollTop);
    if (timeElapsed < 700) requestAnimationFrame(animation);
  }

  function easeInOutQuad(t, b, c, d) {
    t /= d / 2;
    if (t < 1) return (c / 2) * t * t + b;
    t--;
    return (-c / 2) * (t * (t - 2) - 1) + b;
  }

  requestAnimationFrame(animation);
}

// Usage:
scrollToPosition(500); // Scroll to the position of 500 pixels from the top

This code uses the easeInOutQuad function to create a smooth scrolling effect. The window.requestAnimationFrame() method is used to run the animation loop and update the scroll position. The scrollTop property of the window is updated within the animation function to smoothly scroll to the specified position.

This method does not manipulate the DOM directly, but instead uses the window.scrollTo() method to change the scroll position.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.