All threads / How do you make a tab stay "active" after a page reload
Ask A Question


You’re not receiving notifications from this thread.

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

Christian Whitesides asked in 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"
    when "user_books/want_to_read"
    when "user_books/reading_now"
    when "user_books/finished"
    when "user_books/recommended"
    when "user_books/dropped"

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)

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. 👍

Join the discussion

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

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

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

    logo Created with Sketch.

    Screencast tutorials to help you learn Ruby on Rails, Javascript, Hotwire, Turbo, Stimulus.js, PostgreSQL, MySQL, Ubuntu, and more. Icons by Icons8

    © 2023 GoRails, LLC. All rights reserved.