Rust frontend, yew-router simple tutorial

Rust frontend, yew-router simple tutorial

Jan 12, 2023·

2 min read

Table of contents

No heading

No headings in the article.

Yew Router is a router that can be used in Yew applications in Rust and WebAssembly. Here is a simple tutorial describing how to use Yew Router in the Yew application:

  1. First, you will need to import the dependency for Yew Router in your Cargo.toml file. You can do this by adding the following lines:

[dependencies]
yew = "0.20"
yew-router = "0.17.0"

2. Then, you need to import Yew Router in your Rust application’s code.

use yew::prelude::*;
use yew_router::prelude::*;

3. Now, you can specify your application’s routing table. You can do this by adding the following code:

fn switch(routes: RootRoutes) -> Html {
match routes {
RootRoutes::About => html! { },
RootRoutes::Root => html! {},
}
}

#[derive(Clone, Routable, PartialEq, Debug)]
pub enum RootRoutes {
#[at("/")]
Root,
#[at("/about")]
About,
}

5. Finally, you will need to use the BrowserRouter component in your application’s HTML to create route links. You can do this by adding the following code:

#[function_component(RouteOutlet)]
pub fn route_outlet() -> Html {
html! {

<Switch render={switch} />

}
}

<ul>
<li><Link<RootRoutes> to={RootRoutes::Root}>{ "Home" }</Link<RootRoutes>></li>
<li><Link<RootRoutes> to={RootRoutes::About}>{ "About" }</Link<RootRoutes>></li>
</ul>

6. Now, you can navigate to different routes in your application using <Link> anywhere in your code. For example, you can navigate to the About route anywhere in your application by using the following code:

<Link<RootRoutes> to={RootRoutes::About}>{ "About" }</Link<RootRoutes>>