Home > Software engineering >  how to put Custom Next and Prev Scroll Buttons for div react
how to put Custom Next and Prev Scroll Buttons for div react

Time:11-14

I have two buttons. Prev and Next Button. On below, I have one horizontal div with multiple items with scroll bar.
Here's the UI looks like:

enter image description here

The Scroll Bar working good. But I have prev and next buttons. When I click on two buttons, it should scroll left and right. I tried. But I don't know how to make it in react.

Here's the Code I tried:

export default function App() {
  const data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
  return (
    <div>
      <div
        style={{
          display: "flex",
          justifyContent: "flex-end",
          gap: "50px",
          marginBottom: "30px"
        }}
      >
        <div style={{ cursor: "pointer" }}>Prev</div>
        <div style={{ cursor: "pointer" }}>Next</div>
      </div>
      <div
        style={{
          display: "flex",
          gap: "150px",
          overflow: "scroll",
          backgroundColor: "aqua"
        }}
      >
        {data.map((item, index) => (
          <div>item {item}</div>
        ))}
      </div>
      <div></div>
    </div>
  );
}

I don't know how to make it. Please help me with some solutions.

CodePudding user response:

You can use scrollLeft property and useRef. Here is my solution.

export default function App() {
  const data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
  const ref = React.useRef(null)

  const handleScroll = (offset) => {
    if (ref.current) {
      ref.current.scrollLeft  = offset;
    }
  }

  return (
    <div>
      <div
        style={{
          display: "flex",
          justifyContent: "flex-end",
          gap: "50px",
          marginBottom: "30px"
        }}
      >
        <div onClick={() => handleScroll(-30)} style={{ cursor: "pointer" }}>Prev</div>
        <div onClick={() => handleScroll(30)} style={{ cursor: "pointer" }}>Next</div>
      </div>
      <div
        style={{
          display: "flex",
          gap: "150px",
          overflow: "scroll",
          backgroundColor: "aqua"
        }}
        ref={ref}
      >
        {data.map((item, index) => (
          <div key={index}>item {item}</div>
        ))}
      </div>
      <div></div>
    </div>
  );
}
  • Related