Components

Dropdown

A Stimulus controller to create a dropdown.


Installation

  1. Install the package

    Terminal
    $ yarn add @stimulus-components/dropdown
    
  2. Register the controller in your application

    app/javascript/controllers/index.js
    import { Application } from '@hotwired/stimulus'
    import Dropdown from '@stimulus-components/dropdown'
    
    const application = Application.start()
    application.register('dropdown', Dropdown)
    

This controller uses stimulus-use/use-transition under the hood. You can change the animation behavior as you want.

Example

Dropdown

Usage

app/views/index.html
<div data-controller="dropdown" class="relative">
  <button type="button" data-action="dropdown#toggle click@window->dropdown#hide">Options</button>

  <div
    data-dropdown-target="menu"
    class="hidden transition transform origin-top-right absolute right-0"
    data-transition-enter-from="opacity-0 scale-95"
    data-transition-enter-to="opacity-100 scale-100"
    data-transition-leave-from="opacity-100 scale-100"
    data-transition-leave-to="opacity-0 scale-95"
  >
    <a href="#" data-action="dropdown#toggle">Account settings</a>
    <a href="#" data-action="dropdown#toggle">Support</a>
    <a href="#" data-action="dropdown#toggle">License</a>
  </div>
</div>

TailwindCSS is used in this example, but it's up to you to style the dropdown as you want.

Extending Controller

You can use inheritance to extend the functionality of any Stimulus component:

app/javascript/controllers/dropdown_controller.js
import Dropdown from "@stimulus-components/dropdown"

export default class extends Dropdown {
  connect() {
    super.connect()
    console.log("Do what you want here.")
  }

  toggle(event) {
    super.toggle()
  }

  hide(event) {
    super.hide(event)
  }
}

This controller will automatically have access to targets defined in the parent class.

If you override the connect, disconnect or any other methods from the parent, you'll want to call super.method() to make sure the parent functionality is executed.