How to Add Swipe Effect in React?

Sometimes, we want to add Swipe effect in React.

In this article, we’ll look at how to add Swipe effect in React.

Add Swipe Effect in React

To add Swipe effect in React, we can add the onTouchStart on onTouchMove and onTouchEnd props and set them to event handler functions.

For instance, we write:

import React from "react";

export default function App() {
  return (
    <div>
      <div
        onTouchStart={(touchStartEvent) => console.log(touchStartEvent)}
        onTouchMove={(touchMoveEvent) => console.log(touchMoveEvent)}
        onTouchEnd={() => console.log("onTouchEnd")}
        onMouseDown={(mouseDownEvent) => console.log(mouseDownEvent)}
        onMouseMove={(mouseMoveEvent) => console.log(mouseMoveEvent)}
        onMouseUp={() => console.log("onMouseUp")}
        onMouseLeave={() => console.log("onMouseLeave")}
      >
        swipe
      </div>
    </div>
  );
}

to add them.

The onTouchStart handler will run when we start swiping.

onTouchMove will run when we’re swiping.

onTouchEnd will run when we’re done swiping.

We also add mouse event handlers for compatibility with non-touch devices.

Conclusion

To add Swipe effect in React, we can add the onTouchStart on onTouchMove and onTouchEnd props and set them to event handler functions.