Blog>
Snippets

Implementing Animations with Tailwind CSS in Next.js

Demonstrate how to implement custom animations with Tailwind CSS in a Next.js application, focusing on interactive UI elements.
import { useState } from 'react';

export default function AnimatedButton() {
  const [isAnimating, setIsAnimating] = useState(false);

  function triggerAnimation() {
    setIsAnimating(true);
    // Reset the animation state after it ends
    setTimeout(() => setIsAnimating(false), 1000); // Duration of the animation
  }

  return (
    <button
      className={`p-4 text-white bg-blue-500 rounded transition ${isAnimating ? 'animate-bounce' : ''}`}
      onClick={triggerAnimation}
    >
      Click me!
    </button>
  );
}
This code snippet creates a React component using Next.js that displays an animated button. When the button is clicked, it applies the Tailwind CSS 'animate-bounce' animation class for 1 second and then removes it.
module.exports = {
  // ...
  plugins: [
    // ...
    require('@tailwindcss/forms'),
    require('@tailwindcss/typography'),
    require('tailwindcss-animation-delay'), // Needed if we want to use animation-delay
  ],
  // ...
  theme: {
    extend: {
      // ...
      keyframes: {
        bounce: {
          '0%, 100%': { transform: 'translateY(-25%)', animationTimingFunction: 'cubic-bezier(0.8,0,1,1)' },
          '50%': { transform: 'translateY(0)', animationTimingFunction: 'cubic-bezier(0,0,0.2,1)' },
        },
      },
      animation: {
        bounce: 'bounce 1s infinite',
      },
    },
  },
  // ...
}
This code snippet modifies the Tailwind CSS config file to add custom animations. It requires the 'tailwindcss-animation-delay' plugin to use animation delays and defines a custom 'bounce' animation with keyframes.