DEV Community

Patrick Moore
Patrick Moore

Posted on

Building Animated Buttons with react-awesome-button in React

react-awesome-button is a library for creating animated, interactive buttons in React applications. It provides various button styles, animations, and states to create engaging user interfaces with smooth transitions and visual feedback. This guide walks through setting up and creating animated buttons using react-awesome-button with React, from installation to a working implementation.

Prerequisites

Before you begin, make sure you have:

  • Node.js version 14.0 or higher installed
  • npm, yarn, or pnpm package manager
  • A React project (version 16.8 or higher) or create-react-app setup
  • Basic knowledge of React hooks (useState)
  • Familiarity with JavaScript/TypeScript
  • Understanding of CSS animations

Installation

Install react-awesome-button and required CSS:

npm install react-awesome-button
Enter fullscreen mode Exit fullscreen mode

Or with yarn:

yarn add react-awesome-button
Enter fullscreen mode Exit fullscreen mode

Or with pnpm:

pnpm add react-awesome-button
Enter fullscreen mode Exit fullscreen mode

After installation, your package.json should include:

{
  "dependencies": {
    "react-awesome-button": "^6.0.0",
    "react": "^18.0.0",
    "react-dom": "^18.0.0"
  }
}
Enter fullscreen mode Exit fullscreen mode

Project Setup

Import the CSS file in your main entry file:

// src/index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import 'react-awesome-button/dist/styles.css';
import App from './App';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);
Enter fullscreen mode Exit fullscreen mode

First Example / Basic Usage

Let's create a simple animated button. Create a new file src/ButtonExample.jsx:

// src/ButtonExample.jsx
import React from 'react';
import AwesomeButton from 'react-awesome-button';
import 'react-awesome-button/dist/styles.css';

function ButtonExample() {
  const handleClick = () => {
    console.log('Button clicked!');
    alert('Button clicked!');
  };

  return (
    <div style={{ padding: '20px', textAlign: 'center' }}>
      <h2>Basic Awesome Button Example</h2>
      <AwesomeButton
        type="primary"
        onPress={handleClick}
      >
        Click Me
      </AwesomeButton>
    </div>
  );
}

export default ButtonExample;
Enter fullscreen mode Exit fullscreen mode

Update your App.jsx:

// src/App.jsx
import React from 'react';
import ButtonExample from './ButtonExample';
import './App.css';

function App() {
  return (
    <div className="App">
      <ButtonExample />
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

This creates a basic animated button with click handling.

Understanding the Basics

react-awesome-button provides several button types and features:

  • Button types: primary, secondary, link, etc.
  • Animations: Various animation effects
  • States: Loading, disabled, success states
  • Sizes: Different button sizes
  • Icons: Support for icons
  • Customization: Extensive styling options

Key concepts:

  • Button types: Use type prop to set button style
  • Event handling: Use onPress for click events
  • States: Control button state with props
  • Animations: Built-in animation effects
  • Styling: Customize with CSS or props

Here's an example with different button types and states:

// src/AdvancedButtonExample.jsx
import React, { useState } from 'react';
import AwesomeButton from 'react-awesome-button';
import 'react-awesome-button/dist/styles.css';

function AdvancedButtonExample() {
  const [loading, setLoading] = useState(false);
  const [success, setSuccess] = useState(false);

  const handleAsyncAction = async () => {
    setLoading(true);
    setSuccess(false);
    // Simulate async operation
    await new Promise(resolve => setTimeout(resolve, 2000));
    setLoading(false);
    setSuccess(true);
    setTimeout(() => setSuccess(false), 2000);
  };

  return (
    <div style={{ padding: '20px', textAlign: 'center' }}>
      <h2>Advanced Button Examples</h2>
      <div style={{ display: 'flex', flexDirection: 'column', gap: '20px', maxWidth: '300px', margin: '0 auto' }}>
        <AwesomeButton type="primary" onPress={() => alert('Primary clicked')}>
          Primary Button
        </AwesomeButton>
        <AwesomeButton type="secondary" onPress={() => alert('Secondary clicked')}>
          Secondary Button
        </AwesomeButton>
        <AwesomeButton type="link" onPress={() => alert('Link clicked')}>
          Link Button
        </AwesomeButton>
        <AwesomeButton
          type="primary"
          loading={loading}
          disabled={loading}
          onPress={handleAsyncAction}
        >
          {success ? 'Success!' : 'Async Action'}
        </AwesomeButton>
      </div>
    </div>
  );
}

export default AdvancedButtonExample;
Enter fullscreen mode Exit fullscreen mode

Practical Example / Building Something Real

Let's build a comprehensive button system with different use cases:

// src/ButtonSystem.jsx
import React, { useState } from 'react';
import AwesomeButton from 'react-awesome-button';
import 'react-awesome-button/dist/styles.css';

function ButtonSystem() {
  const [submitLoading, setSubmitLoading] = useState(false);
  const [deleteLoading, setDeleteLoading] = useState(false);
  const [downloadLoading, setDownloadLoading] = useState(false);

  const handleSubmit = async () => {
    setSubmitLoading(true);
    await new Promise(resolve => setTimeout(resolve, 2000));
    setSubmitLoading(false);
    alert('Form submitted successfully!');
  };

  const handleDelete = async () => {
    if (!confirm('Are you sure you want to delete?')) return;
    setDeleteLoading(true);
    await new Promise(resolve => setTimeout(resolve, 1500));
    setDeleteLoading(false);
    alert('Item deleted!');
  };

  const handleDownload = async () => {
    setDownloadLoading(true);
    await new Promise(resolve => setTimeout(resolve, 2000));
    setDownloadLoading(false);
    alert('Download complete!');
  };

  return (
    <div style={{ padding: '20px', maxWidth: '600px', margin: '0 auto' }}>
      <h1>Button System Examples</h1>

      {/* Form Buttons */}
      <section style={{ marginBottom: '40px', padding: '20px', border: '1px solid #ddd', borderRadius: '8px' }}>
        <h2>Form Buttons</h2>
        <div style={{ display: 'flex', gap: '10px', flexWrap: 'wrap' }}>
          <AwesomeButton
            type="primary"
            loading={submitLoading}
            disabled={submitLoading}
            onPress={handleSubmit}
          >
            Submit
          </AwesomeButton>
          <AwesomeButton
            type="secondary"
            onPress={() => alert('Cancel clicked')}
          >
            Cancel
          </AwesomeButton>
          <AwesomeButton
            type="link"
            onPress={() => alert('Reset clicked')}
          >
            Reset
          </AwesomeButton>
        </div>
      </section>

      {/* Action Buttons */}
      <section style={{ marginBottom: '40px', padding: '20px', border: '1px solid #ddd', borderRadius: '8px' }}>
        <h2>Action Buttons</h2>
        <div style={{ display: 'flex', gap: '10px', flexWrap: 'wrap' }}>
          <AwesomeButton
            type="primary"
            loading={downloadLoading}
            disabled={downloadLoading}
            onPress={handleDownload}
          >
            Download
          </AwesomeButton>
          <AwesomeButton
            type="secondary"
            onPress={() => alert('Share clicked')}
          >
            Share
          </AwesomeButton>
          <AwesomeButton
            type="primary"
            loading={deleteLoading}
            disabled={deleteLoading}
            onPress={handleDelete}
            cssModule={{
              button: 'custom-danger-button'
            }}
          >
            Delete
          </AwesomeButton>
        </div>
      </section>

      {/* Size Variations */}
      <section style={{ marginBottom: '40px', padding: '20px', border: '1px solid #ddd', borderRadius: '8px' }}>
        <h2>Size Variations</h2>
        <div style={{ display: 'flex', gap: '10px', alignItems: 'center', flexWrap: 'wrap' }}>
          <AwesomeButton type="primary" size="small" onPress={() => alert('Small clicked')}>
            Small
          </AwesomeButton>
          <AwesomeButton type="primary" size="medium" onPress={() => alert('Medium clicked')}>
            Medium
          </AwesomeButton>
          <AwesomeButton type="primary" size="large" onPress={() => alert('Large clicked')}>
            Large
          </AwesomeButton>
        </div>
      </section>
    </div>
  );
}

export default ButtonSystem;
Enter fullscreen mode Exit fullscreen mode

Add custom styles in App.css:

/* src/App.css */
.custom-danger-button {
  background: linear-gradient(135deg, #dc3545 0%, #c82333 100%);
}

.custom-danger-button:hover {
  background: linear-gradient(135deg, #c82333 0%, #bd2130 100%);
}
Enter fullscreen mode Exit fullscreen mode

Now create a form with button states:

// src/FormWithButtons.jsx
import React, { useState } from 'react';
import AwesomeButton from 'react-awesome-button';
import 'react-awesome-button/dist/styles.css';

function FormWithButtons() {
  const [formData, setFormData] = useState({
    name: '',
    email: ''
  });
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [submitSuccess, setSubmitSuccess] = useState(false);

  const handleInputChange = (e) => {
    const { name, value } = e.target;
    setFormData(prev => ({ ...prev, [name]: value }));
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    setIsSubmitting(true);
    setSubmitSuccess(false);

    // Simulate API call
    await new Promise(resolve => setTimeout(resolve, 2000));

    setIsSubmitting(false);
    setSubmitSuccess(true);
    setFormData({ name: '', email: '' });

    setTimeout(() => setSubmitSuccess(false), 3000);
  };

  return (
    <div style={{ padding: '20px', maxWidth: '500px', margin: '0 auto' }}>
      <h2>Form with Awesome Buttons</h2>
      <form onSubmit={handleSubmit}>
        <div style={{ marginBottom: '16px' }}>
          <label style={{ display: 'block', marginBottom: '4px', fontWeight: '500' }}>
            Name:
          </label>
          <input
            type="text"
            name="name"
            value={formData.name}
            onChange={handleInputChange}
            required
            style={{
              width: '100%',
              padding: '8px',
              border: '1px solid #ddd',
              borderRadius: '4px',
              boxSizing: 'border-box'
            }}
          />
        </div>
        <div style={{ marginBottom: '16px' }}>
          <label style={{ display: 'block', marginBottom: '4px', fontWeight: '500' }}>
            Email:
          </label>
          <input
            type="email"
            name="email"
            value={formData.email}
            onChange={handleInputChange}
            required
            style={{
              width: '100%',
              padding: '8px',
              border: '1px solid #ddd',
              borderRadius: '4px',
              boxSizing: 'border-box'
            }}
          />
        </div>
        <div style={{ display: 'flex', gap: '10px' }}>
          <AwesomeButton
            type="primary"
            loading={isSubmitting}
            disabled={isSubmitting || submitSuccess}
            onPress={handleSubmit}
          >
            {submitSuccess ? 'Submitted!' : 'Submit'}
          </AwesomeButton>
          <AwesomeButton
            type="secondary"
            disabled={isSubmitting}
            onPress={() => setFormData({ name: '', email: '' })}
          >
            Clear
          </AwesomeButton>
        </div>
      </form>
    </div>
  );
}

export default FormWithButtons;
Enter fullscreen mode Exit fullscreen mode

Update your App.jsx:

// src/App.jsx
import React from 'react';
import ButtonSystem from './ButtonSystem';
import FormWithButtons from './FormWithButtons';
import './App.css';

function App() {
  return (
    <div className="App">
      <ButtonSystem />
      <FormWithButtons />
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

This example demonstrates:

  • Different button types
  • Loading states
  • Success states
  • Form integration
  • Size variations
  • Custom styling
  • Async operations

Common Issues / Troubleshooting

  1. Button not displaying: Make sure you've imported the CSS file (import 'react-awesome-button/dist/styles.css'). The button requires styles to render correctly.

  2. Animations not working: Check that the CSS is properly imported. Animations are handled by the CSS file, so ensure it's loaded.

  3. Loading state not showing: Use the loading prop to show loading state. Make sure you're managing the loading state in your component.

  4. Click not working: Use onPress prop instead of onClick. The library uses onPress for event handling.

  5. Styling conflicts: Use the cssModule prop to apply custom CSS classes. You can override default styles using CSS.

  6. Button types: Available types include primary, secondary, link, etc. Check the documentation for all available types.

Next Steps

Now that you have an understanding of react-awesome-button:

  • Explore all available button types and animations
  • Learn about advanced customization options
  • Implement button groups and toolbars
  • Add icons to buttons
  • Create custom button themes
  • Learn about other button libraries
  • Check the official repository: https://github.com/rcaferati/react-awesome-button

Summary

You've successfully set up react-awesome-button in your React application and created animated buttons with different types, states, and use cases. react-awesome-button provides an easy way to create engaging, animated buttons with smooth transitions and visual feedback.

SEO Keywords

react-awesome-button
React animated button
react-awesome-button tutorial
React button component
react-awesome-button installation
React interactive button
react-awesome-button example
React button library
react-awesome-button setup
React button animations
react-awesome-button customization
React button states
react-awesome-button loading
React button styles
react-awesome-button getting started

Top comments (0)