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

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:

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'

6 Likes