Unlock the Power of Rust: Building a Frontend Web App with Yew

Rust, a systems programming language, has traditionally been associated with backend web development. However, with the advent of WebAssembly (Wasm), Rust can now be used to build rich frontend applications. In this article, we’ll explore how to create a basic frontend web app using the Yew web framework.

Getting Started with Yew

To begin, ensure you have Rust 1.50 or higher and Trunk installed. Trunk is a build and pipeline tool for Rust-based Wasm applications that provides a local development server, automatic file watching, and simplifies sending Rust code to Wasm.

Creating a Rust Project

Let’s create a new Rust project with the necessary dependencies. Add the following code to your Cargo.toml file:
toml
[dependencies]
yew = "0.19.0-rc.1"
yew-router = "0.19.0-rc.1"
anyhow = "1.0.40"
serde = { version = "1.0.125", features = ["derive"] }
wasm-bindgen = "0.2.74"

With the setup complete, let’s dive into building our app.

HTML Setup with Trunk

Create a minimal index.html file in your project root using Trunk:
“`html





Todo App



“`
Setting up TodoApp with Basic Routing

Implement basic routing by creating a TodoApp struct and defining the Component trait:
“`rust
struct TodoApp {
link: ComponentLink,
todos: Option>,
fetch_task: Option,
}

impl Component for TodoApp {
type Message = Msg;
type Properties = ();

fn create(_: Self::Properties, link: ComponentLink<Self>) -> Self {
    //...
}

fn view(&self) -> Html {
    //...
}

fn update(&mut self, msg: Self::Message) -> ShouldRender {
    //...
}

}
“`
Fetching Data

Fetch data from JSONPlaceholder using the FetchService:
“`rust
impl Component for TodoApp {
//…

fn update(&mut self, msg: Self::Message) -> ShouldRender {
    match msg {
        Msg::MakeReq => {
            let fetch_task = FetchService::fetch("https://jsonplaceholder.typicode.com/todos")
               .then(|response| {
                    //...
                });
            self.fetch_task = Some(fetch_task);
        }
        //...
    }
}

}
“`
Displaying Data

Display the fetched data using the view method:
“`rust
impl Component for TodoApp {
//…

fn view(&self) -> Html {
    html! {
        <div>
            { self.todos.as_ref().map(|todos| {
                //...
            }).unwrap_or_else(|| {
                //...
            })}
        </div>
    }
}

}
“`
Adding Navigation

Implement basic navigation using Yew-router:
“`rust
enum AppRoute {
Home,
Detail(u32),
}

impl Switch for AppRoute {
fn switch(self) -> Html {
match self {
AppRoute::Home => {
//…
}
AppRoute::Detail(id) => {
//…
}
}
}
}
“`
Running the App

Run the app using trunk serve and access it at http://localhost:8080. You now have a beautiful, Rust-based frontend web application!

Conclusion

With the advent of WebAssembly, Rust can now be used to build frontend web applications, expanding development opportunities for developers. While the libraries, frameworks, and technologies used in this post are still early in development, they are already maturing and stable, opening up possibilities for larger projects in the future.

Debugging with LogRocket

Debugging Rust applications can be challenging, especially when users experience issues that are hard to reproduce. LogRocket provides full visibility into web frontends for Rust apps, allowing you to monitor and track performance, automatically surface errors, and track slow network requests and load time. Try LogRocket today!

Leave a Reply

Your email address will not be published. Required fields are marked *