2

I'm having trouble implementing smooth scrolling to an element based on React's useRef that will work in any of the modern browser without any lag in the animation. This seems hard and is why I'm asking for assistance.

Have tried to use the scrollIntoView({ behavior: 'smooth', block: 'start' }) which works nice in Google Chrome and Firefox, but Safari does not seem to work. Tried to install a polyfill (https://www.npmjs.com/package/smoothscroll-polyfill) for support in Safari and other browsers, but when testing on an Iphone 8 in Safari, its not good enough as the scroll animation lags.

Thinking on creating a util function called ScrollToElement which takes an element ref or something and try to animate it myself, but would like some help to get started, as I haven't really played with css animations that much.

Could some help me in the correct direction on solving this problem, so I can smoothly scroll to any div that works in any browsers?

const elementRef = useRef<HTMLDivElement>(null)

Utils function

export const scrollToElement = (element: HTMLDivElement) => {

}

I'm doing typescript btw.

Pixel
  • 349
  • 1
  • 8
  • 17
  • I've used `smoothscroll-polyfill` in my [portfolio website](https://muhammadali.io), can you play around with the navigation and let me if its lagging? If yes, then I'll have to change it as well. – Muhammad Ali May 22 '20 at 16:02

1 Answers1

1

Here's how you can do it with existing smoothscroll-polyfill and useRef hook

const {
  useRef
} = React;

const App = () => {
  const elementRef = useRef(null);
  
  const onClick = () => {
    elementRef.current.scrollIntoView({behavior: 'smooth'});
  }

  return <div className = "container">
    <button className="button" onClick = {onClick}>Scroll down</button>
    <div className = "content">
      <div ref={elementRef}>Element</div>
    </div>
  </div>
}

ReactDOM.render( <
  App / > ,
  document.getElementById('root')
);
.content {
  height: 800px;
  background: #00000033;
  display: flex;
  flex-direction: column;
  justify-content: flex-end;
}
<script>
window.__forceSmoothScrollPolyfill__ = true;
</script>
<script src="https://unpkg.com/react/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
<script src="https://unpkg.com/smoothscroll-polyfill@0.4.4/dist/smoothscroll.js"></script>

<div id="root"></div>
Józef Podlecki
  • 10,453
  • 5
  • 24
  • 50
  • But this is not what I'm asking for? Have problems using this technique as it is not smooth on ios devices – Pixel May 22 '20 at 16:36
  • [Perhaps you need also this css webkit trick](https://stackoverflow.com/questions/37313872/vertical-scrolling-in-ios-not-smooth) – Józef Podlecki May 22 '20 at 16:38