kalipts
kalipts

Reputation: 1317

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

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 .

Upvotes: 4

Views: 3651

Answers (2)

Drew Reese
Drew Reese

Reputation: 203091

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

Upvotes: 4

Zachary Haber
Zachary Haber

Reputation: 11037

Scroll behavior requires using DOM manipulation to some extent, however there is an easier way to get a reference to the node you want to scroll. You can create a ref in a hook component using:

const containerRef = useRef();

<div
    className="container"
    ref={containerRef}
    id="container"
    onWheel={onWheel}
  ></div>

And then you can get your container element using: const container = containerRef.current;

https://codesandbox.io/s/nifty-boyd-m5fg3?file=/src/App.js

Upvotes: 3

Related Questions