shadcn/ui on Rails

repository·main·Indexed 21 days ago

https://github.com/aviflombaum/shadcn-rails

A collection of customizable, copy-pasteable components for Rails applications inspired by the shadcn/ui React ecosystem. It provides a shadcn-ui gem with generators to install components, Stimulus controllers for interactivity, and Rails helpers for view rendering, allowing developers to own and customize their component library without a static npm dependency.

Tokens
2.8K
Snippets
10
Records
16
Agent score
71%

What's inside shadcn-rails

  1. Understand the shadcn/ui on Rails model

    main

    shadcn/ui on Rails is not a traditional component library that you install as a dependency. Instead, it is a collection of reusable components designed to be copied and pasted directly into your Rails application.

    Key characteristics:

    • No npm dependency: You do not install it via a package manager.
    • Full ownership: Once you copy a component, the code is yours to customize and own.
    • Purpose: It serves as a reference and a starting point to help you build your own custom component library within a Rails environment.
    • Implementation: While based on shadcn/ui, these components are adapted for Rails and may not be 1:1 copies due to the shift from React/Radix to Rails-compatible implementations, though the goal is to maintain the same API and accessibility features.
  2. How to use component helpers

    main

    To use a component in your Rails views, call the render_<component> method provided by the component's helper. These helpers are located in app/helpers/components/<component>_helper.rb.

    Workflow

    1. Call the helper: The helper method (e.g., render_dialog) accepts a hash of arguments (**options) and an optional block.
    2. Capture content: The helper typically uses capture(&block) to turn the block's content into a string.
    3. Render the partial: The helper then renders the component's partial, located at app/views/components/ui/_<component>.html.erb, passing the captured content and options along.

    Using Blocks and content_for

    For components that require specific sections (like a dialog trigger vs. dialog content), the helper uses content_for to capture specific parts of the block. You call specialized sub-helpers within the main component block to define these sections.

    # Example of the pattern used in Components::DialogHelper
    module Components::DialogHelper
      def render_dialog(**options, &block)
        content = capture(&block) if block
        render "components/ui/dialog", content: content, **options
      end
    
      def dialog_trigger(&block)
        content_for :dialog_trigger, capture(&block), flush: true
      end
    
      def dialog_content(&block)
        content_for :dialog_content, capture(&block), flush: true
      end
    end
  3. Configure component options

    main

    Most components accept DOM, HTML, or data-related options. These are passed as a hash to the render_<component> method.

    Depending on the specific component implementation, these options are either explicitly defined in the helper's method signature or passed through via a double-splat **options argument to ensure they are applied to the underlying HTML elements in the partial.

  4. Understand the shadcn/ui on Rails approach

    main

    This project is not a traditional component library that you install as a dependency. Instead, it is a collection of re-usable components built with Radix UI and Tailwind CSS that you copy and paste into your own application.

    By copying the code directly, you take full ownership of the components, allowing you to customize them to your specific needs without being constrained by an external library's abstractions.

  5. Configure TailwindCSS dependencies for shadcn/ui

    main

    The components require TailwindCSS and specific npm packages to function and render correctly.

    Option 1: Quick Setup

    The easiest way is to install tailwindcss-animate, which includes the necessary dependencies.

    npm install -D tailwindcss-animate

    Note: If your application does not use npm packages (e.g., you use importmaps), create a package.json first using echo '{}' >> package.json to allow the Tailwind CLI to compile the themes.

    Option 2: Individual Dependencies

    If you prefer to install them individually, you need:

    • @tailwindcss/forms
    • @tailwindcss/aspect-ratio
    • @tailwindcss/typography
    • @tailwindcss/container-queries
    • tailwindcss-animate
  6. Use the shadcn-rails gem to facilitate component installation

    main

    The shadcn-rails gem provides a generator designed to help you copy working component code from the reference application into your own Rails application. Because component files often require specific setup to function correctly, the gem handles the necessary configuration and scaffolding for you.

    For detailed instructions on using the generator, refer to the generator documentation.

  7. Manual Installation of shadcn/ui components

    main

    If you are not using the gem, you can manually install components by copying files from the shadcn-rails repository.

    Prerequisites

    1. TailwindCSS: Install via the tailwindcss-rails gem:
      ./bin/bundle add tailwindcss-rails
      ./bin/rails tailwindcss:install
    2. Tailwind Configuration: Manually configure tailwind.config.js with the required colors, keyframes, and plugins (including tailwindcss-animate, @tailwindcss/forms, etc.).
    3. CSS Variables: Add the required CSS variables (for colors like --background, --primary, --ring, etc.) to your app/assets/stylesheets/application.tailwind.css within a @layer base block for both :root and .dark modes.

    Copying Component Files

    To use a specific component (e.g., Accordion), you must copy three types of files from the source repository:

    1. Stimulus Controller: app/javascript/controllers/components/ui/[component]_controller.js (for JS functionality).
    2. Rails Helper: app/helpers/components/[component]_helper.rb (for easy view rendering).
    3. View Template: app/views/components/ui/_[component].html.erb (the HTML structure).

    Usage Example

    Once copied, render the component in your view using the helper:

    <%= render_accordion title: "Did you know?",
                      description: "You can wrap shadcn helpers in any
                                    component library you want!" %>
  8. Install shadcn/ui components using Rails generators

    main

    The shadcn-ui generator allows you to copy component code from the shadcn/ui library directly into your Rails application.

    Important Warning: Re-running a generator for a component you have already installed will overwrite the existing files in your application. If you have made custom edits to a component's code, those changes will be lost when you re-run the generator. Think of re-running the generator as a clean reinstallation of that specific component.

    Before running the generator, ensure your application has the necessary prerequisites, such as Tailwind CSS and the shadcn stylesheet. The generator will attempt to reconcile these dependencies automatically if they are missing.

    rails generate shadcn-ui <component_name>
  9. Set up the development environment

    main

    If you are contributing to or developing the shadcn-rails repository itself, follow these steps to set up your local environment:

    1. Clone the repository.
    2. Run the setup script to install dependencies:
      bin/setup
    3. Start the Tailwind CSS watcher and the Rails server. Note that the watcher and the server must be run in separate processes to ensure debuggers function correctly:
      bin/dev
      (This command starts the tailwind watcher; you must then run rails s separately.)
    bin/setup
    bin/dev
    # Then run rails s in a separate terminal
  10. Configure shadcn CSS and Tailwind settings

    main

    After installing the gem, you must manually ensure the CSS and Tailwind configurations are correctly linked.

    1. Include shadcn.css

    Ensure app/assets/stylesheets/shadcn.css (added by the gem) is imported in your application.tailwind.css file:

    @import "shadcn.css";
    @tailwind base;
    @tailwind components;
    @tailwind utilities;

    2. Update tailwind.config.js

    You must include the config/shadcn.tailwind.js file in your tailwind.config.js. You can do this by requiring it and spreading the configuration. This ensures all shadcn-specific theme settings and plugins are applied.

    To use the shadcn settings as your base configuration:

    const shadcnConfig = require("./shadcn.tailwind.js");
    
    module.exports = {
      ...shadcnConfig,
    };

    To merge with an existing configuration, add ...shadcnConfig to the end of your export object so it can override or extend your current settings.

  11. Locate and use Stimulus controllers for UI components

    main

    Many shadcn/ui components in this project are paired with a Stimulus controller to manage interactivity. These controllers are located in app/javascript/controllers/ui/<component>_controller.js.

    Important Compatibility Note: This project currently manages JavaScript dependencies using importmaps. If your Rails application is not using importmaps, these Stimulus controllers may not function correctly.

    app/javascript/controllers/ui/<component>_controller.js