karns
karns

Reputation: 5877

How to do Stateful Bootstrap 4 Tab Navigation in Rails 6

Currently I have a Rails 6 app using Bootstrap 4's tab component. The tab component works slick! However, I find it to be a terrible user experience when refreshing or navigating forward then back resets the tab to the default tab. I'm going to say that keeping it in the URL (instead of cookies or localstorage) is a requirement because the need to share links. See image - upon page load the details tab is open, then I click on contacts tab, refresh then reverts back to the details tab. Goal is on that refresh to keep the contacts tab open.

enter image description here

Question 1) How can one keep the state of the tab in the URL? Best practices, things to consider, etc.

Question 2) Perhaps my desired approach is wrong from the start. What would be good alternatives?

Upvotes: 0

Views: 273

Answers (1)

Ben Trewern
Ben Trewern

Reputation: 1740

You can do it like so:

In your view do something like:

<%
  tabs = %w(Details Contacts Projects Orders Batches)
  selected_tab = params[:tab] || tabs.first
%>

<ul class="nav nav-tabs">
  <% tabs.each do |tab| %>
    <%= render 'shared/tab', tab: tab, active: selected_tab == tab %>
  <% end %>
</ul>

then a partial shared/_tab.html.erb

<li class="nav-item">
  <%= link_to title, company_path(@company, selected_tab: tab),
                     class: "nav-link#{ active ? ' active' : '' }" %>
</li>

Upvotes: 1

Related Questions