Search code examples
javavaadin

Vaadin: Propper navigation between views with Tab component


i have created a navigation menu bar with Vaadin and i was wondering how i can attach a view or a link to each tab so on click it can redirect me to the corresponding view. I have managed to get a workaround but i think this approach is flawed:

Tabs tabs = new Tabs(new Tab("Login"), new Tab("Register"));
        tabs.setOrientation(Tabs.Orientation.VERTICAL);
        tabs.addSelectedChangeListener(event -> {
            if (event.getSelectedTab().getLabel().equalsIgnoreCase("Login")) {
                UI.getCurrent().navigate(LoginView.class);
            } else if (event.getSelectedTab().getLabel().equalsIgnoreCase("Register")) {
                UI.getCurrent().navigate(RegisterView.class);
            }
        });

I did not find an individual clickListener event on the Tab component which is weird to me. Also noticed that i can get the UI attached to the tab with tabName.getUI() method, however i cannot find a way to attach it.

Help me find the propper way to navigate with tabs! Thanks in advance!


Solution

  • In Vaadin 14 you can add components to Tabs. So instead of doing just new Tab("Login") you can do something like the follows:

    private Tab createMenuItem(String title, VaadinIcon icon, Class<? extends Component> target) {
        RouterLink link = new RouterLink(null,target);
        if (icon != null) link.add(icon.create());
        link.add(title);
        Tab tab = new Tab();
        tab.add(link);
        return tab;
    }
    

    Naturally RouterLink is not the only option, if you like you could use also Button and use click listener of the button to call navigation, etc. There is quite a lot options here.