useRef helper function behavior 'smooth'

Viewed 600

I am trying to create a helper function that I can use throughout my React application, but the behavior 'smooth' does not seem to be working.

const scrollRef = useRef()

const handleScroll = (ref) => {
return ref.current.scrollTo({ left: ref.current.scrollLeft -= 500, behavior: 'smooth' })
}

handleScroll(scrollRef)

it is scrolling to the position, but not smoothly. If I do not use this helper function it works fine. Do you have any ideas how to make this work?

2 Answers

you can add smooth scroll behavior by adding a small CSS style.

.your-element-class {
  scroll-behavior: smooth
}

Just to make sure of how you're using it, is the function running on click event, or something else?

The code snippet below works fine.

import { useRef } from "react";

export default function App() {
  const scrollRef = useRef(null);

  const handleScroll = (ref) => {
    if (ref.current) {
      return window.scrollTo({ left: ref.current.scrollLeft -= 500, behavior: 'smooth' })
    }
  }
  return (
    <div style={{ height: '300vh', width: '200vw' }} onClick={() => handleScroll(scrollRef)}>
      <div ref={scrollRef} style={{ height: '100vh', width: '150vw', background: 'black' }}></div>
      <div style={{ height: '100vh', width: '150vw', background: 'green' }}></div>
    </div>
  );
}

Are you using it differently?

Related