How to disable scroll on touch?

Viewed 268

I have a component in react on which touchmove event should be disabled. I have tried the following but it does not work.

parentRef.current.addEventListener("touchMove", e => e.preventDefault(), false)
3 Answers

You can check if this device has innerWidth below certain pixels then set overflow:hidden and height & width to 100vh & 100vw respectively to the parentRef in useEffect

You can simply use the touch-action property in your CSS file to remove the scroll event from your html body or an element. Add the below code in your code.

touch-action: none;
-ms-touch-action: none;

To prevent scrolling using CSS on React rendered components, we can set the overflow CSS property to hidden with JavaScript.

For instance, we write:

import React, { useEffect } from "react";

export default function App() {
  useEffect(() => {
    document.body.style.overflow = "hidden";
  }, []);

  return <div>hello world</div>;
}

to set the overflow CSS of the body element to hidden when the component mounts with:

document.body.style.overflow = "hidden";

The useEffect callback only runs when the component mounts since we passed in an empty array as the 2nd argument of useEffect.

Related