Skip to content

Commit

Permalink
Use keyed lists in tutorial example (#2948)
Browse files Browse the repository at this point in the history
* Use keyed lists in tutorial example

The example should follow best practices such as using keyed lists.

* Add keys explanation when it is first introduced

* Fix link to keyed lists

* Add forgotten key prop
  • Loading branch information
Allan committed Nov 8, 2022
1 parent 3b4fa88 commit a5f844d
Showing 1 changed file with 9 additions and 5 deletions.
14 changes: 9 additions & 5 deletions website/docs/tutorial/index.mdx
Expand Up @@ -243,10 +243,14 @@ mapping it to `html!` and collecting it as `Html`:

```rust ,ignore
let videos = videos.iter().map(|video| html! {
<p>{format!("{}: {}", video.speaker, video.title)}</p>
<p key={video.id}>{format!("{}: {}", video.speaker, video.title)}</p>
}).collect::<Html>();
```

:::tip
Keys on list items helps Yew keep track of which items have changed in the list, resulting in faster re-renders. [It is always recommended to use keys in lists](/concepts/html/lists.mdx#keyed-lists).
:::

And finally we need to replace the hardcoded list of videos with the `Html` we created from data:

```rust ,ignore {6-10}
Expand Down Expand Up @@ -301,7 +305,7 @@ struct VideosListProps {
#[function_component(VideosList)]
fn videos_list(VideosListProps { videos }: &VideosListProps) -> Html {
videos.iter().map(|video| html! {
<p>{format!("{}: {}", video.speaker, video.title)}</p>
<p key={video.id}>{format!("{}: {}", video.speaker, video.title)}</p>
}).collect()
}
```
Expand Down Expand Up @@ -333,7 +337,7 @@ Now, we can update our `App` component to make use of `VideosList` component.
fn app() -> Html {
// ...
- let videos = videos.iter().map(|video| html! {
- <p>{format!("{}: {}", video.speaker, video.title)}</p>
- <p key={video.id}>{format!("{}: {}", video.speaker, video.title)}</p>
- }).collect::<Html>();
-
html! {
Expand Down Expand Up @@ -385,8 +389,8 @@ Then we modify the `VideosList` component to pass the "emit" the selected video
+ };

html! {
- <p>{format!("{}: {}", video.speaker, video.title)}</p>
+ <p onclick={on_video_select}>{format!("{}: {}", video.speaker, video.title)}</p>
- <p key={video.id}>{format!("{}: {}", video.speaker, video.title)}</p>
+ <p key={video.id} onclick={on_video_select}>{format!("{}: {}", video.speaker, video.title)}</p>
}
}).collect()
}
Expand Down

0 comments on commit a5f844d

Please sign in to comment.