Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

horizontally scroll a table with mouse wheel in react without DOM Selector?

Tags:

reactjs

I am building a table horizontally scroll. But it has DOM selector. How I build it with out DOM Selector. Have any way to do it with state ?

const onWheel = e => {
  e.preventDefault();
  const container = document.getElementById("container");
  const containerScrollPosition = document.getElementById("container").scrollLeft;
  container.scrollTo({
    top: 0,
    left: containerScrollPosition + e.deltaY,
    behaviour: "smooth"
  });
};

my demo: https://codesandbox.io/s/silly-lamport-2do0l?file=/src/App.js .

like image 961
kalipts Avatar asked Oct 22 '25 04:10

kalipts


1 Answers

Using document.getElementById is a react anti-pattern. Use a react ref to access a DOM node.

refs and the dom

Since you have a functional component you can use the useRef hook, otherwise, the createRef can be used for a class-based component.

useRef

Moved the onWheel handler into the component so the ref is in scope. Also removed the optional behavior option, it was misspelled and using the default behavior, which is what you want anyway.

function App() {
  const onWheel = e => {
    e.preventDefault();
    const container = scrollRef.current;
    const containerScrollPosition = scrollRef.current.scrollLeft;

    container.scrollTo({
      top: 0,
      left: containerScrollPosition + e.deltaY,
    });
  };

  const scrollRef = useRef(null);

  const num = 50;
  let points_th = [];

  for (let i = 0; i < num; i++) {
    points_th.push(<th>Points</th>);
  }

  let row_1 = render_row("Jill", "Smith", 50, num);
  let row_2 = render_row("Eva", "Jackson", 94, num);
  let row_3 = render_row("Adam", "Johnson", 67, num);
  return (
    <div>
      <div
        ref={scrollRef}
        className="container"
        id="container"
        onWheel={onWheel}
      >
        <table>
          <tr>
            <th>First Name</th>
            <th>Last Name</th>
            {points_th}
          </tr>
          {row_1}
          {row_2}
          {row_3}
        </table>
      </div>
    </div>
  );
}

Edit horizontal scroll using ref

like image 155
Drew Reese Avatar answered Oct 23 '25 18:10

Drew Reese



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!