Okay, let's create a fully-featured, animated button component using React and Tailwind CSS.
This component will include:
- Multiple Variants:
primary, secondary, success, danger, outline, ghost.
- Sizes:
sm, md, lg.
- Loading State: Shows a spinner and disables interactions.
- Disabled State: Visual feedback and prevents clicks.
- Icon Support: Integrates an icon alongside text.
- Fun Animations:
- Hover Effects: Background color change, shadow growth.
- Active Effect: Slight scale down on click.
- Text/Icon Shift: Subtle horizontal shift on hover.
- Ripple Effect: A beautiful click animation that expands from the click point.
- Prop Passthrough: Allows any standard
<button> props to be passed.
- Custom ClassName: Allows users to add their own Tailwind classes to extend or override default styles.
Setup (if you don't have it already)
- Create React App (if needed):
npx create-react-app my-button-app --template typescript # or just basic
cd my-button-app
- Install Tailwind CSS:
npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p
- Configure
tailwind.config.js:
/** @type {import('tailwindcss').Config} */
module.exports = {
content: [
"./src/**/*.{js,jsx,ts,tsx}",
],
theme: {
extend: {
// Custom Keyframes for Ripple Effect
keyframes: {
ripple: {
'0%': { transform: 'scale(0)', opacity: '0.2' },
'100%': { transform: 'scale(1)', opacity: '0' },
},
},
// Apply Animation to Keyframes
animation: {
ripple: 'ripple 0.6s linear forwards',
},
},
},
plugins: [],
}
- Add Tailwind Directives to
src/index.css (or src/App.css):
@tailwind base;
@tailwind components;
@tailwind utilities;
- Install
clsx (for easily combining class names) and lucide-react (for icons):
npm install clsx lucide-react
Component Code (src/components/Button.jsx or src/components/Button.tsx)
// src/components/Button.jsx (or .tsx)
import React, { useState, useEffect, useCallback } from 'react';
import clsx from 'clsx'; // For conditional class names
// Simple Spinner component
const Spinner = () => (
<svg
className="animate-spin h-5 w-5 text-current"
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
>
<circle
className="opacity-25"
cx="12"
cy="12"
r="10"
stroke="currentColor"
strokeWidth="4"
></circle>
<path
className="opacity-75"
fill="currentColor"
d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
></path>
</svg>
);
const Button = ({
children,
onClick,
disabled = false,
loading = false,
variant = 'primary',
size = 'md',
icon: IconComponent, // Renamed to avoid confusion, it will be a React component like <ArrowRight />
className, // Custom classes for the button itself
...props // Allows passing any other native button props (e.g., type="submit")
}) => {
const [ripples, setRipples] = useState([]);
// Base classes applied to all buttons
const baseClasses = clsx(
"inline-flex items-center justify-center font-semibold rounded-lg",
"transition-all duration-300 ease-in-out",
"focus:outline-none focus:ring-2 focus:ring-opacity-75",
"disabled:opacity-50 disabled:cursor-not-allowed",
"group relative overflow-hidden", // 'group' for hover effects on children, 'relative' for ripple, 'overflow-hidden' for ripple containment
{
"shadow-md hover:shadow-lg active:scale-95": !loading // Shadow and scale only when not loading
}
);
// Variant-specific classes
const variantClasses = {
primary: "bg-blue-600 text-white hover:bg-blue-700 focus:ring-blue-400",
secondary: "bg-gray-200 text-gray-800 hover:bg-gray-300 focus:ring-gray-400",
success: "bg-green-600 text-white hover:bg-green-700 focus:ring-green-400",
danger: "bg-red-600 text-white hover:bg-red-700 focus:ring-red-400",
outline: "bg-transparent border border-blue-600 text-blue-600 hover:bg-blue-50 focus:ring-blue-400",
ghost: "bg-transparent text-blue-600 hover:bg-blue-50 focus:ring-blue-400 shadow-none", // No shadow for ghost
};
// Size-specific classes
const sizeClasses = {
sm: "px-3 py-1 text-sm gap-1",
md: "px-4 py-2 text-base gap-2",
lg: "px-6 py-3 text-lg gap-3",
};
// Icon size classes
const iconSizeClasses = clsx(
size === 'sm' && 'h-4 w-4',
size === 'md' && 'h-5 w-5',
size === 'lg' && 'h-6 w-6'
);
// Handle click and ripple effect
const handleClick = useCallback((event) => {
if (loading || disabled) return;
// Ripple effect logic
const button = event.currentTarget;
const rect = button.getBoundingClientRect();
const size = Math.max(rect.width, rect.height) * 2; // Make ripple big enough to cover
const x = event.clientX - rect.left - size / 2;
const y = event.clientY - rect.top - size / 2;
const newRipple = {
id: Date.now(),
x,
y,
size,
};
setRipples((prevRipples) => [...prevRipples, newRipple]);
// Call the original onClick prop
if (onClick) {
onClick(event);
}
}, [loading, disabled, onClick]); // Dependencies for useCallback
// Remove ripples after animation completes
useEffect(() => {
if (ripples.length > 0) {
const timer = setTimeout(() => {
setRipples((prevRipples) => prevRipples.slice(1));
}, 600); // Matches the ripple animation duration in tailwind.config.js
return () => clearTimeout(timer);
}
}, [ripples]);
return (
<button
onClick={handleClick}
disabled={disabled || loading}
className={clsx(
baseClasses,
variantClasses[variant],
sizeClasses[size],
className // Allows overriding or extending default styles
)}
{...props} // Pass through any other props
>
{loading ? (
<Spinner />
) : (
<>
{IconComponent && (
<span className="transition-transform duration-200 group-hover:-translate-x-0.5">
<IconComponent className={iconSizeClasses} />
</span>
)}
<span className="transition-transform duration-200 group-hover:translate-x-0.5">
{children}
</span>
</>
)}
{/* Ripple elements */}
{ripples.map((ripple) => (
<span
key={ripple.id}
className="absolute bg-white rounded-full opacity-0 pointer-events-none animate-ripple"
style={{
left: ripple.x,
top: ripple.y,
width: ripple.size,
height: ripple.size,
}}
/>
))}
</button>
);
};
export default Button;
Usage Example (src/App.js or src/App.tsx)
// src/App.js (or .tsx)
import React, { useState } from 'react';
import Button from './components/Button';
import { Mail, Settings, CheckCircle, XCircle, Download, Ghost } from 'lucide-react'; // Example icons from lucide-react
function App() {
const [loading1, setLoading1] = useState(false);
const [loading2, setLoading2] = useState(false);
const handleClick1 = () => {
setLoading1(true);
setTimeout(() => setLoading1(false), 2000); // Simulate async operation
};
const handleClick2 = () => {
setLoading2(true);
setTimeout(() => setLoading2(false), 2000); // Simulate async operation
};
return (
<div className="min-h-screen bg-gray-100 p-8 flex flex-col items-center space-y-8">
<h1 className="text-4xl font-bold text-gray-800 mb-8">React & Tailwind Button Showcase</h1>
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 max-w-4xl w-full">
{/* Primary Buttons */}
<div className="bg-white p-6 rounded-lg shadow-md flex flex-col items-center space-y-4">
<h2 className="text-xl font-semibold">Primary Buttons</h2>
<Button onClick={() => alert('Primary Clicked!')} variant="primary" size="sm">
Small Primary
</Button>
<Button onClick={() => alert('Primary Clicked!')} variant="primary" size="md">
Medium Primary
</Button>
<Button onClick={() => alert('Primary Clicked!')} variant="primary" size="lg">
Large Primary
</Button>
<Button onClick={handleClick1} loading={loading1} variant="primary" icon={Mail}>
{loading1 ? 'Sending...' : 'Send Mail'}
</Button>
<Button disabled variant="primary">
Disabled Primary
</Button>
</div>
{/* Secondary Buttons */}
<div className="bg-white p-6 rounded-lg shadow-md flex flex-col items-center space-y-4">
<h2 className="text-xl font-semibold">Secondary Buttons</h2>
<Button onClick={() => alert('Secondary Clicked!')} variant="secondary" size="sm" icon={Settings}>
Settings
</Button>
<Button onClick={() => alert('Secondary Clicked!')} variant="secondary" size="md">
Medium Secondary
</Button>
<Button onClick={handleClick2} loading={loading2} variant="secondary">
{loading2 ? 'Loading...' : 'Load Data'}
</Button>
<Button disabled variant="secondary">
Disabled Secondary
</Button>
</div>
{/* Success Buttons */}
<div className="bg-white p-6 rounded-lg shadow-md flex flex-col items-center space-y-4">
<h2 className="text-xl font-semibold">Success Buttons</h2>
<Button onClick={() => alert('Success Clicked!')} variant="success" size="md" icon={CheckCircle}>
Complete Task
</Button>
<Button disabled variant="success">
Disabled Success
</Button>
</div>
{/* Danger Buttons */}
<div className="bg-white p-6 rounded-lg shadow-md flex flex-col items-center space-y-4">
<h2 className="text-xl font-semibold">Danger Buttons</h2>
<Button onClick={() => alert('Danger Clicked!')} variant="danger" size="md" icon={XCircle}>
Delete Item
</Button>
<Button disabled variant="danger">
Disabled Danger
</Button>
</div>
{/* Outline Buttons */}
<div className="bg-white p-6 rounded-lg shadow-md flex flex-col items-center space-y-4">
<h2 className="text-xl font-semibold">Outline Buttons</h2>
<Button onClick={() => alert('Outline Clicked!')} variant="outline" size="md" icon={Download}>
Download File
</Button>
<Button disabled variant="outline">
Disabled Outline
</Button>
</div>
{/* Ghost Buttons */}
<div className="bg-white p-6 rounded-lg shadow-md flex flex-col items-center space-y-4">
<h2 className="text-xl font-semibold">Ghost Buttons</h2>
<Button onClick={() => alert('Ghost Clicked!')} variant="ghost" size="md" icon={Ghost}>
Ghost Mode
</Button>
<Button disabled variant="ghost">
Disabled Ghost
</Button>
</div>
{/* Custom ClassName Example */}
<div className="bg-white p-6 rounded-lg shadow-md flex flex-col items-center space-y-4 col-span-full">
<h2 className="text-xl font-semibold">Custom Styling</h2>
<Button
onClick={() => alert('Custom Blue Clicked!')}
variant="primary"
size="lg"
icon={Mail}
className="!bg-purple-600 hover:!bg-purple-700 !shadow-xl !ring-purple-400"
>
Purple Button
</Button>
<Button
onClick={() => alert('Another Custom Clicked!')}
variant="secondary"
size="md"
className="uppercase tracking-widest text-sm hover:!bg-teal-100 !text-teal-700 !border-teal-500 !shadow-none"
>
Custom Secondary
</Button>
</div>
</div>
</div>
);
}
export default App;
Explanation of Features & Animations:
-
baseClasses:
inline-flex items-center justify-center: Makes the button content (text and icon) align nicely.
font-semibold rounded-lg: Standard button look.
transition-all duration-300 ease-in-out: Applies a smooth transition to all animatable properties (like background-color, shadow, transform) over 300ms.
focus:outline-none focus:ring-2 focus:ring-opacity-75: Removes the default browser focus outline and adds a custom Tailwind ring for better accessibility and aesthetics.
disabled:opacity-50 disabled:cursor-not-allowed: Visual feedback for disabled state.
group relative overflow-hidden:
group: Crucial for applying hover effects to child elements (like the text and icon spans).
relative: Needed for positioning the absolute ripple spans inside the button.
overflow-hidden: Hides the parts of the ripple that extend beyond the button's bounds.
shadow-md hover:shadow-lg active:scale-95: Standard shadow on button, larger shadow on hover, and a slight shrink (scale-95) when the button is actively pressed.
-
variantClasses & sizeClasses: These objects map the variant and size props to specific Tailwind utility classes, making the component highly configurable.
-
loading State:
- If
loading is true, the Spinner component is rendered instead of the children and IconComponent.
- The
disabled attribute is applied, preventing further clicks.
- Shadow and scale effects are removed during loading to prevent visual glitches.
-
icon: IconComponent:
- The
icon prop expects a React component (e.g., <Mail /> from lucide-react).
- It's wrapped in a
<span> to control its animation.
-
Text/Icon Shift Animation (group-hover:-translate-x-0.5 and group-hover:translate-x-0.5):
This component provides a robust and visually engaging button solution for your React applications with Tailwind CSS!