Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect correctly mouse wheel in ReactJS

Maybe someone knows how to fix my bag.

I have a problem with detecting the wheel up and down, also it's a problem with MAC OS trackpad.

I need to increase the state by 1 (see code) if I rotate down and decrease by 1 if up. BUT IF I SCROLL UP IT'S SO MANY DETECTIONS, AND THE SAME IF DOWN. I don't need a page scroll.

My code looks:

const pages = [
  { name: "About", page: <About />, id: 1 },
  { name: "Contact", page: <Contact />, id: 2 },
  { name: "Hire Us", page: <HireUs />, id: 3 },
  { name: "Home", page: <Home />, id: 4 },
  { name: "Works", page: <Works />, id: 5 }
];

class App extends Component {
  constructor() {
    super();
    this.state = {
      item: 1
    };
  }
  scrollSite(y) {
    const pageLenght = pages.length - 1;
    if (y < 0) {
      console.log("slide up");
      if (this.state.item < pageLenght) {
        this.setState({ item: this.state.item + 1 });
      } else if (this.state.item === pageLenght) {
        this.setState({ item: 0 });
      }
    } else {
      console.log("slide down");
      if (this.state.item === 0) {
        this.setState({ item: this.state.item - 1 });
      } else if (this.state.item === pageLenght) {
        this.setState({ item: 0 });
      }
    }
  }
  componentDidMount() {
    window.addEventListener("wheel", e => {
      this.scrollSite(e.wheelDelta);
    });
  }
  render() {
    const { item } = this.state;
    return (
      <div className="container">
        <div className="navigation">
          {pages.map(page => (
            <div key={page.id}>{page.name}</div>
          ))}
        </div>
        <div>{pages[item].page}</div>
      </div>
    );
  }
}

export default App;
like image 796
Anon Avatar asked Nov 21 '25 05:11

Anon


1 Answers

You can add event listener using javascript as follows

window.addEventListener("wheel", event => {
 // Your code
});

or you can add onWheel directly on the element

<div onWheel = {(e) => this.onWheel(e)} > 
like image 88
Avinash Rathod Avatar answered Nov 23 '25 20:11

Avinash Rathod