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

  1. void routerLink() {
  2. Div menu = new Div();
  3. menu.add(new RouterLink("Home", HomeView.class));
  4. menu.add(new RouterLink("Greeting", GreetingComponent.class, "default"));
  5. }

GreetingComponent with URL parameter

  1. @Route(value = "greet")
  2. public class GreetingComponent extends Div
  3. implements HasUrlParameter<String> {
  4. @Override
  5. public void setParameter(BeforeEvent event,
  6. String parameter) {
  7. setText(String.format("Hello, %s!", parameter));
  8. }
  9. }

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

  1. NativeButton button = new NativeButton("Navigate to company");
  2. button.addClickListener( e-> {
  3. button.getUI().ifPresent(ui -> ui.navigate("company"));
  4. });
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: