Skip to content

Instantly share code, notes, and snippets.

@josefarias
Last active May 30, 2024 20:26
Show Gist options
  • Save josefarias/80f9673ed36d27dbcc1db9e918b06fc4 to your computer and use it in GitHub Desktop.
Save josefarias/80f9673ed36d27dbcc1db9e918b06fc4 to your computer and use it in GitHub Desktop.
Rails dropdown component using helpers and Tailwind
<nav class="flex justify-end w-full px-4">
<%= dropdown do %>
<%= dropdown_link_to "Profile", edit_user_registration_path %>
<%= dropdown_link_to "Password", edit_account_password_path %>
<%= dropdown_link_to "Social Accounts", social_accounts_path %>
<%= dropdown_link_to "Accounts", accounts_path %>
<%= dropdown_link_to "Billing", subscriptions_path %>
<%= dropdown_link_to "Other Settings", other_settings_path %>
<%= dropdown_button_to "Log out", destroy_user_session_path, method: :delete %>
<% end %>
</nav>
module DropdownsHelper
def dropdown(&block)
tag.details class: "relative" do
concat dropdown_summary
concat dropdown_contents(&block)
end
end
def dropdown_link_to(*args, **kwargs, &block)
light = "text-gray-800 bg-white hover:bg-indigo-50"
dark = "dark:text-gray-50 dark:bg-gray-800 dark:hover:bg-indigo-800"
other = "transition ease-in-out duration-200 whitespace-nowrap no-underline block px-6 py-3"
link_to(*args, **kwargs.merge(class: [ kwargs.delete(:class), light, dark, other ]), &block)
end
def dropdown_button_to(*args, **kwargs, &block)
light = "text-gray-800 bg-white hover:bg-indigo-50 border-gray-200"
dark = "dark:text-gray-50 dark:bg-gray-800 dark:hover:bg-indigo-800 dark:border-gray-700"
other = "w-full text-left font-medium cursor-pointer px-6 py-3 border-t transition ease-in-out duration-200 whitespace-nowrap"
button_to(*args, **kwargs.merge(form: { class: [ kwargs.delete(:class), light, dark, other ] }), &block)
end
private
def dropdown_summary
tag.summary dropdown_chevron, class: "cursor-pointer"
end
def dropdown_chevron
tag.svg xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 20 20", class: "w-4 h-4 fill-current dark:text-gray-100 text-gray-700" do
tag.path d: "M9.293 12.95l.707.707L15.657 8l-1.414-1.414L10 10.828 5.757 6.586 4.343 8z"
end
end
def dropdown_contents(&block)
light = "bg-white border-gray-200"
dark = "dark:bg-gray-900 dark:border-gray-700"
other = "border rounded shadow-md z-10 mt-2 w-56 absolute right-0"
tag.div class: [ light, dark, other ], &block
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment