Open In App

How to Ceate Swipe-able Button in Tailwind CSS and React?

Last Updated : 03 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Creating swipe-enabled buttons in React applications can greatly improve user experience, especially on mobile devices, these buttons are typically used for actions like deleting, sharing, and liking items, in this article we'll show you how to create a swipe-enabled button using Tailwind CSS for styling and React for functionality.

Approach

In this approach, we first create a React project and set up Tailwind CSS for styling. Framer Motion is used to detect swipe gestures, allowing us to add interactive animations for a swipe-enabled button. The button responds to a swipe gesture by moving and revealing additional actions like "Delete." We also handle the swipe state in the component using React's useState hook, ensuring the button's behavior and appearance change based on user interaction. This combination of tools makes it easy to create responsive, mobile-friendly UI elements.

Steps to Create & Configure the Project

Step 1: Create a New React Project

Firstly we have to run the given command to create a new React project.

npx create-react-app swipe-button-demo
cd swipe-button-demo

Step 2: Install Tailwind CSS

When we create a new project We will need to install Tailwind CSS and create a configuration file named tailwind.config.js, we can do this by running following command.

npm install tailwindcss postcss autoprefixer
npx tailwindcss init

Project Structure:

Untitled

Updated Dependencies:

dependencies: {
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"autoprefixer": "^10.4.20",
"framer-motion": "^11.9.0",
"postcss": "^8.4.47",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-scripts": "5.0.1",
"tailwindcss": "^3.4.13",
"web-vitals": "^2.1.4"
}

Step 3: Configure Template Paths

Edit tailwind.config.js file to add content paths for your React files.

JavaScript
/*tailwind.config.js*/
/** @type {import('tailwindcss').Config} */
module.exports = {
    content: [
        "./src/**/*.{js,jsx,ts,tsx}",
    ],
    theme: {
        extend: {},
    },
    plugins: [],
}

Step 4: Add Tailwind Directives

In src/index.css file, add base, components and utilities layers of Tailwind:

@tailwind base;
@tailwind components;
@tailwind utilities;

Step 5: Install Framer Motion

We will use Framer Motion for detecting swipe gestures and animating button.

npm install framer-motion

Step 6: Create the Swipe Button Component

Now create a new file SwipeButton.js in src directory and add following code.

JavaScript
//components/SwipeButton.js
import React, { useState } from 'react';
import { motion } from 'framer-motion';

const SwipeButton = () => {
    const [swiped, setSwiped] = useState(false);

    const handleSwipe = (event, info) => {
        if (info.offset.x < -100) {
            setSwiped(true);
        }
    };

    return (
        <div className="relative w-full
                        max-w-sm mx-auto mt-12">
            <motion.div
                className={`p-4 bg-green-600
                            text-white rounded-lg
                            shadow-lg ${swiped ? 'translate-x-[-100%]' : ''
                    }`}
                drag="x"
                dragConstraints={{ left: 0, right: 0 }}
                onDragEnd={handleSwipe}
                initial={{ x: 0 }}
                animate={{ x: swiped ? -100 : 0 }}
            >
                Swipe Me
            </motion.div>

            {swiped && (
                <div className="absolute top-0
                                right-0 p-4 bg-red-500
                                text-white rounded-lg">
                    <button onClick={() => setSwiped(false)}>Delete</button>
                </div>
            )}
        </div>
    );
};

export default SwipeButton;

Step 7: Add the SwipeButton Component to the App

Open src/App.js and import SwipeButton component.

JavaScript
//App.js
import React from 'react';
import SwipeButton from './components/SwipeButton';
import './index.css';

function App() {
    return (
        <div className="min-h-screen bg-gray-100 flex
                        flex-col items-center justify-center">
            {/* Green GeeksforGeeks text */}
            <h1 className="text-green-600
                           text-4xl font-bold
                           mb-8">
                           GeeksforGeeks
                           </h1>

            {/* Swipeable Button */}
            <SwipeButton />
        </div>
    );
}

export default App;

Step 8: Run the Application

Now you can start your development server.

npm start

Output: Open your browser and navigate to http://localhost:3000.


Next Article

Similar Reads