Home > database >  What is the proper way of manipulating scroll of overflowed flexbox in ReactJS
What is the proper way of manipulating scroll of overflowed flexbox in ReactJS

Time:06-26

Consider the following structure:

.container {
  width: 200px;
  height: 100px;
  overflow: auto;
  overflow-y: hidden;
}

.container p {
  width: 300px;
  height: 100px;
  background-color: yellow;
}
<div >
  <p>Sample Text1, Sample Text2, Sample Text3</p>
</div>
<button onclick="handleScrollLeft()">Left</button>
<button onclick="handleScrollRight()">Right</button>

Because I'm working in ReactJS, my real code looks more like this:

    export function Slider() {
    
      const handleScrollLeft = () => {
      }
    
      const handleScrollRight = () => {
      }
    
      return (
        <>
          <div className="container">
            <p>Sample Text1, Sample Text2, Sample Text3</p>
          </div>
          <button onClick="handleScrollLeft">Left</button>
          <button onClick="handleScrollRight">Right</button>
        </>
      );
    }

With those 2 buttons I would like to change the scroll value (move left and right respectively). I'm not sure how to handle this kind of change:

  1. In useEffect? (I don't want to force re-render, just expand the scroll functionality to those 2 buttons)
  2. Create custom hook? (Same concern)
  3. Or should I directly modify that DOM element in the handler functions? (I know this is a big no-no in React)

I'm really confused on which approach is correct, any advise or solution with further explanation on why would be appreciated

CodePudding user response:

You can use the useRef hook and the element.scrollBy method.

const STEP = 40;

export function Slider() {
  const scrollable = useRef(null);
  
  const handleScrollLeft = () => {
    scrollable.current.scrollBy(-STEP, 0);
  }
    
  const handleScrollRight = () => {
    scrollable.current.scrollBy(STEP, 0);
  }
    
  return (
    <>
      <div className="container" ref={scrollable}>
        <p>Sample Text1, Sample Text2, Sample Text3</p>
      </div>

      <button onClick="handleScrollLeft">Left</button>
      <button onClick="handleScrollRight">Right</button>
    </>
  );
}

You can also use this sandbox as an example.

  • Related