Navigating Between Routes
You can use the RouterLink
component to create links that lead to route targets in the application.
RouterLink sample for navgation target with and without URL parameter
void routerLink() {
Div menu = new Div();
menu.add(new RouterLink("Home", HomeView.class));
menu.add(new RouterLink("Greeting", GreetingComponent.class, "default"));
}
GreetingComponent with URL parameter
@Route(value = "greet")
public class GreetingComponent extends Div
implements HasUrlParameter<String> {
@Override
public void setParameter(BeforeEvent event,
String parameter) {
setText(String.format("Hello, %s!", parameter));
}
}
It is also possible to navigate with normal <a href="company">
type links but these will cause a page reload. Navigation with RouterLink
instead fetches the contents of the new component, which is updated in place without reloading the page.
Tip | By adding a router-link attribute to a regular link, you tell the framework that it should handle navigation without reloads, e.g. <a router-link href=”company”>Go to the company page</a> . |
To trigger navigation from the server side, use UI.navigate(String)
, where the string parameter is the location to navigate to. Also available is , UI.navigate(Class<? extends Component> navigationTarget)
or navigate(Class<? extends C> navigationTarget, T parameter)
so you don’t have to generate the route string manually. This will trigger the updating of the browser location and add a new history state entry. An example navigation to the company
route target when clicking a button:
Java
NativeButton button = new NativeButton("Navigate to company");
button.addClickListener( e-> {
button.getUI().ifPresent(ui -> ui.navigate("company"));
});
Note | Router links will work even if the session has expired so you should prefer to use those instead of handling navigation server side. |
See also: