Build a sample app

First create a new Rust library (important: create a library, not a binary by passing the --lib flag):

1. cargo new --lib yew-app && cd yew-app

Add yew and wasm-bindgen to your dependencies (refer here for the latest version)

1. [package]
2. name = "yew-app"
3. version = "0.1.0"
4. authors = ["Yew App Developer <name@example.com>"]
5. edition = "2018"

7. [lib]
8. crate-type = ["cdylib", "rlib"]

10. [dependencies]
11. yew = "0.17"
12. wasm-bindgen = "0.2.67"

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

1. use wasm_bindgen::prelude::*;
2. use yew::prelude::*;

4. struct Model {
5. link: ComponentLink<Self>,
6. value: i64,
7. }

9. enum Msg {
10. AddOne,
11. }

13. impl Component for Model {
14. type Message = Msg;
15. type Properties = ();
16. fn create(_: Self::Properties, link: ComponentLink<Self>) -> Self {
17. Self {
18. link,
19. value: 0,
20. }
21. }

23. fn update(&mut self, msg: Self::Message) -> ShouldRender {
24. match msg {
25. Msg::AddOne => self.value += 1
26. }
27. true
28. }

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. }

37. fn view(&self) -> Html {
38. html! {
39. <div>
40. <button onclick=self.link.callback(|_| Msg::AddOne)>{ "+1" }</button>
41. <p>{ self.value }</p>
42. </div>
43. }
44. }
45. }

47. #[wasm_bindgen(start)]
48. pub fn run_app() {
49. App::<Model>::new().mount_to_body();
50. }

This template sets up your root Component, called Model which shows a button that updates itself when you click it. Take special note of App::<Model>::new().mount_to_body() 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 App::<Model>::new().mount_to_body_with_props(..).

Finally, add an index.html file into a new folder named static in your app.

1. mkdir static
1. <!doctype html>
2. <html lang="en">
3. <head>
4. <meta charset="utf-8">
5. <title>Yew Sample App</title>
6. <script type="module">
7. import init from "./wasm.js"
8. init()
9. </script>
10. </head>
11. <body></body>
12. </html>

Run your App!

Using wasm-pack is the preferred way to get up and running. If you haven’t already, install wasm-pack with cargo install wasm-pack and then build and start a development server by running:

1. wasm-pack build --target web --out-name wasm --out-dir ./static

wasm-pack generates a bundle in the ./static directory with your app’s compiled WebAssembly along with a JavaScript wrapper which will load your application’s WebAssembly binary and run it.

Then, use your favorite web server to serve the files under ./static. For example:

1. cargo +nightly install miniserve
2. miniserve ./static --index index.html