You are currently viewing the docs for Dioxus 0.4.3 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]Router]

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(cx: Scope) -> Element {
    render! {
        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]

The Routable]route(path)]

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("/")]
    // If the name of the component and variant are the same you can omit the component and props name
    // If they are different you can specify them like this:
    // #[route("/", ComponentName, PropsName)]
    Home {},
}

All other hooks and components the router provides can only be used as a descendant of a Router]

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(cx: Scope, route: Vec<String>) -> Element {
    render! {
        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