You are currently viewing the docs for Dioxus 0.5.7 which is no longer maintained.

Creating Our First Route

In this chapter, we will start utilizing Dioxus Router and add a homepage and a

Fundamentals

The core of the Dioxus Router is the Routable macro and the Router component.

Routable is a trait for anything that can:

  • Be parsed from a URL
  • Be turned into a URL
  • Be rendered as to a Element

Let's create a new router. First, we need an actual page to route to! Let's add a homepage component:

src/first_route.rs
#[component]
fn Home() -> Element {
    rsx! { h1 { "Welcome to the Dioxus Blog!" } }
}

Creating Routes

We want to use Dioxus Router to separate our application into different "pages".

To start using Dioxus Router, we need to use the Routable macro.

The Routable macro takes an enum with all of the possible routes in our application. Each variant of the enum represents a route and must be annotated with the #[route(path)] attribute.

src/first_route.rs
#![allow(non_snake_case)]
use dioxus::prelude::*;
use dioxus_router::prelude::*;

/// An enum of all of the possible routes in the app.
#[derive(Routable, Clone)]
enum Route {
    // The home page is at the / route
    #[route("/")]
    Home {},
}

The Router component will provide a router context for all the inner components and hooks to use. You usually will want to place this at the top of your components tree.

src/first_route.rs
fn App() -> Element {
    rsx! { Router::<Route> {} }
}

If you head to your application's browser tab, you should now see the textWelcome to Dioxus Blog! when on the root URL (http://localhost:8080/). If

This is because we told Dioxus Router to render the Home component only when/.

Fallback Route

In our example, when a route doesn't exist Dioxus Router doesn't render anything. Many sites also have a "404" page when a path does not exist. Let's add one to our site.

First, we create a new PageNotFound component.

src/catch_all.rs
#[component]
fn PageNotFound(route: Vec<String>) -> Element {
    rsx! {
        h1 { "Page not found" }
        p { "We are terribly sorry, but the page you requested doesn't exist." }
        pre { color: "red", "log:\nattemped to navigate to: {route:?}" }
    }
}

Next, register the route in the Route enum to match if all other routes fail.

src/catch_all.rs
#[derive(Routable, Clone)]
enum Route {
    #[route("/")]
    Home {},
    // PageNotFound is a catch all route that will match any route and placing the matched segments in the route field
    #[route("/:..route")]
    PageNotFound { route: Vec<String> },
}

Now when you go to a route that doesn't exist, you should see the page not found

Conclusion

In this chapter, we learned how to create a route and tell Dioxus Router what/. We also created a 404 page to