Rust: Building Web Frontend with Yew

Pudding Entertainment
6 min readApr 20, 2023
Generated by Bing Image Creator

If you’re looking to build web applications that are both performant and reliable, you might want to consider using Rust and Yew. While still in early stages of development, Yew already provides enough functionality to build a product that is fast and memory safe.

In this article, we’ll explore the benefits of using Yew for web development and provide you with the motivation you need to start building your next web application with this powerful framework.

Prerequisites

I’m using Rust version 1.68.2. This tutorial assumes prior knowledge of Rust and concentrates more on practical usage of the language.

I’ll be using the project I’m actively working on at the moment — illuvi-analytics. The relevant parts of it will be stripped into self-sufficient code snippets, and you are welcome to check the entire project out.

If you are curious to know what this project is about please check out the Background section of my previous tutorial.

There are 3 parts in this tutorial: Setup, Component Creation, Router

Part 1. Setup

I’m assuming that you have Rust, Yew and trunk configured already. If not, check this Getting Started tutorial out first.

In this section, I’ll guide you through the process of configuring project’s static files, including the images folder, CSS styles, and index.html. Additionally, we’ll set up Cargo.toml and main.rs files, ensuring that the project is properly set up.

Let’s begin with the Cargo.toml file, note the inline comments to better understand the choice of dependencies:

Next, we will set up the index.html file with Bootstrap 5 and FontAwesome 5 for improved styling:

Take a closer look at the index.html file and you’ll notice that the last two links are referencing style.css and img. The style.css file is used for any customizations on top of Bootstrap 5, while the img folder is used for storing any necessary static images for your website

Lastly, let’s prepare the main.rs file:

It’s important to mention a couple of things here. First, there are various loggers available in Yew, but for this tutorial, we’ve chosen wasm-logger because of its smooth integration with the log crate that is widely used in the Rust community. Second, it’s worth noting that you can directly reference any Bootstrap classes in your HTML code, as seen in the p class=”text-white” example. This is a great way to quickly and easily style your website using the Bootstrap framework.
With all the necessary dependencies and static files in place the Setup section is now complete, and we are now ready to move on to the next part — Component Creation, where the actual web page will be created.

Part 2. Component Creation

In this section, I’ll guide you through the process of creating the first function_component, which will be a simple page displaying a collection of images.

Note! This tutorial focuses solely on the frontend part. However, it’s important to keep in mind that there is a backend server running behind the scenes.

Yew offers two flavors of components — function components and Struct components. Here we’ll be focusing on function components as they are the recommended way for implementing simple presentation logic.

Let’s create a new file called home.rs that will serve as the starting page of the website.

Let’s take a closer look at the code. Yew leverages the popular concept of hooks, which allows for cleaner and more modular code. In this example, we use the use_state hook to manage the component’s state, which triggers a re-render whenever the state is updated. We also use the use_effect_with_deps hook to handle side-effects in response to updates in specific dependencies. It is supplied with an empty tuple as dependencies so that the data is loaded only once.
To make a asynchronous API call, the wasm_bindgen_futures::spawn_local function is executed. The api_utils::fetch_single_api_response function and the CollectionData model are project-specific and used for API call. Note that CollectionData contains an image_url pointing to an actual image, name and token_address. Once the API response is received, the state is updated that triggers the re-render of the view.

Note! One thing to keep in mind is that it’s generally a good practice to extract every HTML tag into its own functional component. This reduces boilerplate and makes the code more maintainable.

Now we can use the Home component in the main.rs:

Run trunk serve, navigate to localhost:8080 in your favorite browser and you should be able to see the page:

Before we wrap up this section, I want to emphasize the importance of following established best practices when building a web UI, especially a large one. By adhering to best practices, you’ll be able to create more efficient and maintainable code. If you’re already a web developer familiar with ReactJS, Vue.js, or similar frameworks, you’ll find that many of the principles and techniques you’ve learned are also applicable in Yew. With this in mind, let’s continue our journey into creating robust and efficient web applications with Rust and Yew.

Part 3. Router

In a typical web application, there are usually multiple pages to navigate through. To achieve this in a Single Page Application, a router is used to render different components based on the current URL. The advantage of using a router is that, instead of requesting a new resource every time a link is clicked, the router updates the URL locally and then renders the corresponding component. This can greatly improve the user experience and reduce network requests. To use it in Yew a separate crate — yew-router — should be added to Cargo.toml
Let’s create our own router. This will be placed in a separate file called route.rs. To keep things simple just three routes will be defined: Home, NotFound, and Collection.

There are a few noteworthy things to note in this code snippet. Firstly, you can create routes that include path variables by using a colon (:) notation. Then, we are referencing the Home view created in the previous section within our Router. Finally, the not_found attribute is used as a catch-all for when a path cannot be found.

With this in place, let’s do the last change for main.rs

The last missing piece is to add navigation to the Collection page from the Home page. In order to achieve this we the Link component will be used:

The final result will look like this:

Afterwards

Although Yew is a relatively new framework, it follows the same principles as React and other modern web frameworks, making it easy to pick up for experienced web developers. By combining Rust’s performance and safety with Yew’s ease of use and familiar concepts, we can create powerful web applications that are both fast and reliable. So, whether you are new or a seasoned developer, Yew is definitely worth checking out for your next web project.

Do check out my Yew-powered website https://illuvi-analytics.com

Honorable Mentions

If you’re looking to dive deeper into Yew and gain a more comprehensive understanding of this awesome framework, I highly recommend checking out the Yew course on Brooks Builds YouTube channel. This course offers a thorough walkthrough of Yew’s features and functionality, making it an excellent resource for anyone serious about learning and mastering the framework.

Support

If you like the content you read and want to support the author — thank you very much!

Here is my Ethereum wallet for tips:

0xB34C2BcE674104a7ca1ECEbF76d21fE1099132F0

--

--

Pudding Entertainment

Serious software engineer with everlasting passion for GameDev. Dreaming of next big project. https://pudding.pro