This week’s answer is inspired by a direct question I found on YouTube:
Using Vaadin Framework 8.2, I was able to quickly implement a simple application with a side menu, containing options that change the main content of the UI when they are clicked and keeping the back and forward buttons of the browser usable.
The following is a screenshot of the application:
You can accomplish this by implementing individual Views for each option in the menu:
public class DefaultView extends Composite implements View {...} public class View1 extends Composite implements View {...} public class View2 extends Composite implements View {...}
You can link these views with a URL by using a Navigator
:
Navigator navigator = new Navigator(this, viewContainer); navigator.addView("", DefaultView.class); navigator.addView("view1", View1.class); navigator.addView("view2", View2.class);
Don’t forget to add a default view, otherwise, you would get an exception. A new feature in Vaadin Framework 8.2 allows you to use the HTML History API with the Navigator
class, so that you won’t see any hashbangs (#) in the URL. To activate it, you need to annotate your UI implementation with @PushStateNavigation
:
@PushStateNavigation public class VaadinUI extends UI {...}
You can implement the options in the menu as regular buttons and add click listeners that navigate to the corresponding view. For example:
Button view1 = new Button("View 1", e -> navigator.navigateTo("view1"));
Here’s a video that shows how to implement this from scratch:
As always, you can find the source code on GitHub. Let me know in the comments section, which topics you would like to see in future Community Answers. Stay tuned and see you next time with another community inspired answer!