Tab View In Phoenix

Hello theree,

I’m trying to embed a tab-view in my phoenix app. Does anyone know a JavaScript-free approach to have such a view? Something that looks more or less like this view.

Thanks in advance!

By “JavaScript free” do you mean not having to write JS, or not using JS? Because if it’s the former, LiveView will get the job done. If you want it with no JS at all, there’s probably a CSS only approach out there. But that wouldn’t be Phoenix specific.

As Bumppoman mentioned. You can use the Bulma Framework for that. Btw there is a Framework for composable LiveViews which supports Bulma as well: http://surface-demo.msaraiva.io/uicomponents/Tabs

JavaScript-free this is the way. The article says this version requires a fixed height for the content but I don’t think this is true, I used a similar method for accordions and fixed height was only necessary if I wanted to have linear css transition animations. So I’m pretty sure this restriction can be removed.

It’s easy an implementation, see our app.
All what you have to do is:

  1. in your liveview mount set default tab: socket |> assign(tab: :prevence) and define
    def handle_event("change_tab", %{"tab" => tab}, socket) do
      {:noreply, assign(socket, tab: String.to_atom(tab))}
    end
    
  2. in template
    <div class="tabs is-boxed is-centered">
      <ul>
        <li class="<%= is_active_tab(@tab, :prevence) %>">
          <a
    	    phx-click="change_tab"
    	    phx-value-tab=<%= :prevence %>
          >
    	    <span>Prevence</span>
          </a>
        </li>
        <li class="<%= is_active_tab(@tab, :patient) %>">
          <a
    	    phx-click="change_tab"
    	    phx-value-tab=<%= :patient %>
          >
    	    <span>Pacient</span>
          </a>
        </li>
      </ul>
    </div>
    
  3. in view define function
    def is_active_tab(tab, which_tab) do
      if tab == which_tab do
        "is-active"
      else
        ""
      end
    end
    

EDIT: Ouch, I realized after send post that you asked on Phoenix. This solution is for Phoenix LiveView…

Thanks from the future!

You’re probably better off using JS for this, as you usually don’t need to go back to the server to change tab.

In case anyone else using wants to do something similar, Surface has a tab component too. :slight_smile:

@Menkir sent the link in 2020 but it is outdated now, the new link is here.