New Discussion

Notifications

You’re not receiving notifications from this thread.

How do you make a tab stay "active" after a page reload

6
Javascript

I have a version of your Tabs tailwindcss-stimulus component up and running. However, I'm struggling to figure out how to save an active tab so that it remains active after a page reload. Right now a page reload just kicks the nav back to the tab at index zero...

localStorage seems to be the recommended way to go, but the help I find everywhere is strictly jquery-based. If you have any suggestions, I'd appreciate it! πŸ™

If you set the data index attribute in the HTML when you render the page, that tab will be pre-selected. You'll just have to use a helper in Rails to check the anchor and see if it matches a tab to set the index.

We need to add some code to the code so it can automatically select the index for you when the page loads with a matching anchor still. πŸ‘

Thanks, Chris! Just what I needed. Each tab is tied to an individual controller (in order to avoid writing custom actions), so I just created the following helper:

def index_based_on_controller(controller)
    case controller
    when "user_books"
      0
    when "user_books/want_to_read"
      1
    when "user_books/reading_now"
      2
    when "user_books/finished"
      3
    when "user_books/recommended"
      4
    when "user_books/dropped"
      5
    end
end

Then I used the helper in my div with the navigation, like so:

<div data-controller="filter-statuses" data-filter-statuses-index="<%= index_based_on_controller(params[:controller]) %>" >

Worked out great! If there's a better way to write the helper above, please let me know. Once again, thanks for your help!

That is easy enough! Protip is you can use the index method to find the index integer quickly and simplify this a bit:

irb(main):001:0> ["a", "b", "c"].index("a")
=> 0
irb(main):002:0> ["a", "b", "c"].index("c")
=> 2

So like:

def index_based_on_controller(controller)
  ["user_books", "user_books/want_to_read", "user_books/reading_now", ... etc ].index(controller)
end

That looks much nicer. Thanks for the tip! And thanks again for taking the time to respond. I really appreciate it.

I got some time yesterday to update the library to automatically handle it as long as there's an ID on the tab. πŸ‘

πŸŽ‰ Thanks so much, Chris!

Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 89,127+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.