Build a sample app

First, create a new cargo project:

  1. cargo new yew-app

Open the newly created directory.

First, let’s add yew as a dependencies in the Cargo.toml file:

  1. [package]
  2. name = "yew-app"
  3. version = "0.1.0"
  4. edition = "2018"
  5. [dependencies]
  6. # you can check the latest version here: https://crates.io/crates/yew
  7. yew = "0.18"

Copy the following template into your src/main.rs file:

  1. use yew::prelude::*;
  2. enum Msg {
  3. AddOne,
  4. }
  5. struct Model {
  6. // `ComponentLink` is like a reference to a component.
  7. // It can be used to send messages to the component
  8. link: ComponentLink<Self>,
  9. value: i64,
  10. }
  11. impl Component for Model {
  12. type Message = Msg;
  13. type Properties = ();
  14. fn create(_props: Self::Properties, link: ComponentLink<Self>) -> Self {
  15. Self {
  16. link,
  17. value: 0,
  18. }
  19. }
  20. fn update(&mut self, msg: Self::Message) -> ShouldRender {
  21. match msg {
  22. Msg::AddOne => {
  23. self.value += 1;
  24. // the value has changed so we need to
  25. // re-render for it to appear on the page
  26. true
  27. }
  28. }
  29. }
  30. fn change(&mut self, _props: Self::Properties) -> ShouldRender {
  31. // Should only return "true" if new properties are different to
  32. // previously received properties.
  33. // This component has no properties so we will always return "false".
  34. false
  35. }
  36. fn view(&self) -> Html {
  37. html! {
  38. <div>
  39. <button onclick=self.link.callback(|_| Msg::AddOne)>{ "+1" }</button>
  40. <p>{ self.value }</p>
  41. </div>
  42. }
  43. }
  44. }
  45. fn main() {
  46. yew::start_app::<Model>();
  47. }

This template sets up your root Component, called Model which shows a button that updates itself when you click it. Take special note of yew::start_app::<Model>() inside main() which starts your app and mounts it to the page’s <body> tag. If you would like to start your application with any dynamic properties, you can instead use yew::start_app_with_props::<Model>(..).

Finally, add an index.html file in the root directory of your app:

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8" />
  5. <title>Yew App</title>
  6. </head>
  7. </html>

Run your app

If you haven’t already, install Trunk:

  1. cargo install trunk wasm-bindgen-cli

If you haven’t already installed it, you need to add the wasm32-unknown-unknown target. To install this with Rustup:

  1. rustup target add wasm32-unknown-unknown

Now all you have to do is run the following:

  1. trunk serve

This will start a development server which continually updates the app every time you change something.

Troubleshooting

  • Trunk’s installation failed:

    Make sure you have the development packages of openssl installed. For example, libssl-dev on Ubuntu or openssl-devel on Fedora.