# A tour of how the Widget (Virtual DOM) code in Discourse works

**URL:** https://meta.discourse.org/t/a-tour-of-how-the-widget-virtual-dom-code-in-discourse-works/40347
**Category:** Development
**Created:** [2016 年 2 月 29 日午後 8:18 UTC](https://meta.discourse.org/t/a-tour-of-how-the-widget-virtual-dom-code-in-discourse-works/40347 "2016-02-29T20:18:39Z")
**Posts on this page:** 1
**Showing post:** 18

<div class="post-metadata">

### Author: ![eviltrout](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/eviltrout/32/5275_2.png) [@eviltrout](https://meta.discourse.org/u/eviltrout)
#### Post date: [2016 年 4 月 27 日午後 9:03 UTC](https://meta.discourse.org/t/a-tour-of-how-the-widget-virtual-dom-code-in-discourse-works/40347/18 "2016-04-27T21:03:46Z")

</div>

Whenever a widget has state it needs a `key` so that the virtual dom can apply the state to the same element the next time it is repainted.

It’s pretty easy to do:

```javascript
createWidget('my-widget', {
  buildKey: attrs => `my-widget-${attrs.id}`
});

```

That will build a key using the id of the thing being rendered. If it’s a thing attached to a post you’ll want to use the post’s id for example.

If there is only ever one of your widget, feel free to not even include an id and just return a string, like I do for the header: `buildKey: () => 'header'`

---

_[View the full topic](https://meta.discourse.org/t/a-tour-of-how-the-widget-virtual-dom-code-in-discourse-works/40347)._
